首页 > 解决方案 > QCompleter 中的 QLineEdit 不显示所有项目

问题描述

我正在尝试使用 QCompleter 创建一个菜单应用程序(如 Windows 搜索)。当 QLineEdit 为空时,我想显示完成者的所有项目。它是第一次工作,但是当我开始在 中输入内容时,我从中lineEdit删除所有字符lineEdit,然后按Enter我什么也看不到。我的错误在哪里?

我的代码如下。

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{

    this->wordList << "alpha" << "omega" << "omicron" << "zeta" << "icon";

    this->lineEdit = new QLineEdit(this);

    completer = new QCompleter(wordList, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    lineEdit->setCompleter(completer);
    completer->QCompleter::complete();

    ui->setupUi(this);
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{

    if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter))
    {
        if(lineEdit->text()=="")
        {
            completer->complete();
        }

        if(wordList.contains(lineEdit->text(),Qt::CaseInsensitive))
            qDebug() <<"CATCH IT";
    }
}

你能告诉我吗?

标签: qtmenu

解决方案


您需要在完成者上重置完成前缀。

  if(event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
  {
    if(lineEdit->text().isEmpty())
    {
      lineEdit->completer()->setCompletionPrefix("");
      lineEdit->completer()->complete();
    }
  }

此外,如果意图是仅在行编辑中按下返回时填充它,您将需要创建自己的行编辑来处理它而不是使用主窗口。


推荐阅读