带有QCompleter的QLineEdit不会显示QCompleter的弹出式菜单和空文本字段

2022-03-30 00:00:00 qt4 qt c++

我有一个QLineEdit,与其关联的QCompleter对象。如果用户输入至少一个字符,则会显示QCompleter中的弹出菜单,但当用户删除最后一个字符(从而将该字段留空)时,弹出菜单将消失。有没有办法在QLineEdit的文本为空的情况下也显示它?


解决方案

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

lineEdit->completer()->complete();

您可以这样做:

  • 为您的lineedit定义text已更改槽;
  • 重写窗口的CustomEvent方法;
  • 在TextChanged槽中,每当 Lineedit的文本长度为零;
  • 在CustomEvent方法中,每当收到用户事件时显示完成器;

下面是一个示例:

mainwindow.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 );
};

mainwindow.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()));
}

希望这能有所帮助,致敬

相关文章