我有一个QLineEdit,并且有一个QCompleter对象与之关联。如果用户输入至少一个字符,则显示来自 QCompleter 的弹出菜单,但当用户删除最后一个字符(因此将该字段留空)时,弹出菜单消失。即使 QLineEdit 的文本为空,有没有办法让它显示出来?

最佳答案

您应该能够在使用 QCompleter::complete 插槽擦除行编辑文本后强制显示完成者的弹出窗口:

lineEdit->completer()->complete();
您可以这样做:
  • 为您的 lineedit 定义 textChanged 插槽;
  • 覆盖窗口的 customEvent 方法;
  • textChanged 插槽中的
  • 将用户事件发送到窗口
    lineedit 的文本长度为零;
  • 每当接收到用户事件时,customEvent 方法中的
  • 就会显示完成者;

  • 下面是一个例子:
    主窗口.h:
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    protected:
        void customEvent(QEvent * event);
    
    private:
        Ui::MainWindow *ui;
    
    private slots:
        void on_lineEdit_textChanged(QString );
    };
    
    主窗口.cpp:
    class CompleteEvent : public QEvent
    {
    public:
        CompleteEvent(QLineEdit *lineEdit) : QEvent(QEvent::User), m_lineEdit(lineEdit) { }
    
        void complete()
        {
            m_lineEdit->completer()->complete();
        }
    
    private:
        QLineEdit *m_lineEdit;
    };
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QStringList wordList;
        wordList << "one" << "two" << "three" << "four";
    
        QLineEdit *lineEdit = new QLineEdit(this);
        lineEdit->setGeometry(20, 20, 200, 30);
        connect(lineEdit, SIGNAL(textChanged(QString)), SLOT(on_lineEdit_textChanged(QString )));
    
        QCompleter *completer = new QCompleter(wordList, this);
        completer->setCaseSensitivity(Qt::CaseInsensitive);
        completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
        lineEdit->setCompleter(completer);
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::customEvent(QEvent * event)
    {
        QMainWindow::customEvent(event);
        if (event->type()==QEvent::User)
            ((CompleteEvent*)event)->complete();
    }
    
    void MainWindow::on_lineEdit_textChanged(QString text)
    {
        if (text.length()==0)
            QApplication::postEvent(this, new CompleteEvent((QLineEdit*)sender()));
    }
    
    希望这有帮助,问候

    关于c++ - 带有 QCompleter 的 QLineEdit 不会显示带有空文本字段的 QCompleter 弹出菜单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4857180/

    10-11 18:06