Kaguro
Kaguro

Reputation: 77

QLineEdit in QCompleter doesn't show all items

I am trying to create a menu app (like windows search) with QCompleter. I would like to show all items from completer when the QLineEdit is empty. And it works first time, but when I start typing something into the lineEdit and I delete all characters from lineEdit, and then press Enter I see nothing. Where is my mistake?

My code is below.

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";
    }
}

Could you please advise me?

Upvotes: 1

Views: 1122

Answers (1)

Mason
Mason

Reputation: 71

You need to reset the completion prefix on the completer.

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

Also if the intent is to only have it populate when return is pressed in the line edit, you will want to create your own line edit to handle that versus using the main window.

Upvotes: 3

Related Questions