一、模糊搜索界面由QLineEdit、QCombox组合实现,原始界面如下图所示
二、实现效果如下图所示
三、示例代码
① .h文件
1 #ifndef MAINWINDOW_H
2 #define MAINWINDOW_H
3
4 #include <QMainWindow>
5
6 namespace Ui {
7 class MainWindow;
8 }
9
10 class MainWindow : public QMainWindow
11 {
12 Q_OBJECT
13
14 public:
15 explicit MainWindow(QWidget *parent = nullptr);
16 ~MainWindow();
17
18 void FuzzySearch();
19
20 private:
21 Ui::MainWindow *ui;
22 };
23
24 #endif // MAINWINDOW_H
② cpp文件
1 #include "MainWindow.h"
2 #include "ui_MainWindow.h"
3 #include <QCompleter>
4 #include <QListView>
5
6 MainWindow::MainWindow(QWidget *parent) :
7 QMainWindow(parent),
8 ui(new Ui::MainWindow)
9 {
10 ui->setupUi(this);
11 FuzzySearch();
12 }
13
14 MainWindow::~MainWindow()
15 {
16 delete ui;
17 }
18
19 void MainWindow::FuzzySearch()
20 {
21 QStringList wordList;
22 wordList << "alpha" << "omega" << "omicron" << "zeta";
23 ui->comboBox->addItems(wordList);
24
25 ui->comboBox->setView(new QListView());
26 ui->comboBox->setEditable(true);
27 ui->comboBox->setLineEdit(ui->lineEdit);
28 ui->comboBox->setMaxVisibleItems(5);//下拉列表显示item数
29
30 // QString arrowImagePath = ":/res/combox.png";
31 // ui->comboBox->setStyleSheet("QComboBox {font-family: "Arial"; font-size: 13px; padding: 3px 0x 3px 5px;}"
32 // "QComboBox::drop-down {subcontrol-origin: padding; subcontrol-position: top right; 30 px; border: 0px;}"
33 // "QComboBox::down-arrow {image: url("+ arrowImagePath +");}");
34
35 ui->comboBox->view()->setStyleSheet("QListView {font-family: "Arial"; font-size: 13px; outline: 0px;}"
36 "QListView::item {padding: 3px 0x 3px 5px; border- 0px;}"
37 "QListView::item:selected {background-color: rgb(74, 144, 226);}");
38
39 QCompleter *pCompleter = new QCompleter(wordList, this);
40 ui->lineEdit->setCompleter(pCompleter);
41 pCompleter->setCaseSensitivity(Qt::CaseInsensitive);
42 ui->comboBox->setCompleter(pCompleter);
43
44 ui->lineEdit->clear();
45 }