//输入框添加自动搜索按钮和自动补全控件
void addSerachIconAndCompleterToLineEdit(QLineEdit* lineEdit)
{
QCompleter* completer = new QCompleter(lineEdit);
QStringListModel* stringListModel = new QStringListModel(lineEdit);
completer->setMode(stringListModel);
//显示全部搜索结果
completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
lineEdit->setCompleter(completer);
auto searchAction = new QAction(lineEdit);
searchAction->setIcon(QApplication::style()->standardIcon(QStyle::SP_FileDialogContentsView));
//searchAction->setIcon(":/resource.query.png");
lineEdit->addAction(searchAction, QlineEdit::TrailingPosition);
connect(searchAction, SIGNAL(triggered()), this, SLOT(onSearchAction()));
}
void onSearchAction()
{
QObject* sender = sender();
QAction* action = dynamic_cast<QAction*>(sender);
auto parent = action->parentWidget();
auto lineEdit = dynamic_cast<QLineEdit*>(parent);
auto text = lineEdit->text();
auto completer = lineEdit->completer();
auto model = dynamic_cast<QStringListModel*>(completer->model());
QStingList queryResults;
queryResults<<"AAA"<<"1234";
model->setStringList(queryResults);
completer->complete();
}
来源:oschina
链接:https://my.oschina.net/u/4344310/blog/4292616