单击时显示所有 QCompleter 元素

Show all QCompleter elements on click

有QComboBox和QCompleter。单击 LineEdit 组合框时需要显示所有补充元素。有这个代码:

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);  <-----

在最后一行我设置了EventFilter,它的代码是:

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

它实际工作正常,当您单击时,会显示完整的元素列表,但它只工作一次,当文本随后被完全擦除时,就再也没有任何东西了,您需要再次单击鼠标.我试图使用 focusIn 事件来解决这个问题,但它不起作用,由于某种原因 lineEdit() 没有捕获 Focus 事件。有什么想法吗?

在安装事件过滤器后将此代码放入组合框的 lineEdit 中:

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

还有这个到 MainWindow 的 eventFilter

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

希望对您有所帮助!