Home > Back-end >  Show all QCompleter elements on click
Show all QCompleter elements on click

Time:04-18

There is QComboBox with QCompleter. It is necessary to show all complementer elements when clicking on the LineEdit combobox. There is this code:

completer = new QCompleter(this);
completer->setModel(assignment_contacts);
completer->setCompletionMode(QCompleter::CompletionMode::PopupCompletion);
completer->popup()->setStyleSheet("background-color:rgb(54, 57, 63);"
                              "color:white;");
QFont popupFont = QFont("Segoe UI",12,2);
completer->popup()->setFont(popupFont);


ui->comboBox_NewClientContacts->setEditable(true);
ui->comboBox_NewClientContacts->setInsertPolicy(QComboBox::NoInsert);
ui->comboBox_NewClientContacts->setModel(assignment_contacts);
ui->comboBox_NewClientContacts->setModelColumn(1);
ui->comboBox_NewClientContacts->completer()->setCompletionColumn(1);

ui->comboBox_NewClientContacts->setCompleter(completer);
ui->comboBox_NewClientContacts->lineEdit()->installEventFilter(this);  <-----

In the last line I set the EventFilter, its code is:

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if (object == ui->comboBox_NewClientContacts->lineEdit()){
        if(event->type() == QEvent::MouseButtonPress){
            ui->comboBox_NewClientContacts->lineEdit()->completer()->setCompletionPrefix(ui->comboBox_NewClientContacts->lineEdit()->text());
            ui->comboBox_NewClientContacts->lineEdit()->completer()->complete();
        }
    }
    return false;
}

It works PRACTICALLY as it should, when you click, the full list of elements is shown, but it works once, when the text is subsequently completely erased, there is nothing again, and you need to click the mouse again. I tried to solve this problem using the focusIn event, but it does not work, for some reason lineEdit() does not catch the Focus event. Any ideas?

CodePudding user response:

Put this code after installing event filter to lineEdit of your combobox:

//...
ui->comboBox_NewClientContacts->installEventFilter(this);

And this one to eventFilter of MainWindow:

//...
if (object == ui->comboBox_NewClientContacts){
        if(event->type() == QEvent::KeyRelease && ui->comboBox_NewClientContacts->currentText() == "")
        {
            ui->comboBox_NewClientContacts->completer()->setCompletionPrefix("");
            ui->comboBox_NewClientContacts->completer()->complete();
        }
    }

Hope it helps!

  • Related