Qt QComboBox+QCompleter实现搜索自动匹配

搜索框默认隐藏起来,在界面上按Ctrl+F的时候打开搜索匹配输入框

 1     m_speedSearch = new SpeedSearch(this);
 2     m_speedSearch->initData(QStringList() << "123" << "124" << "110" << "111");
 3     m_speedSearch->hide();
 4 
 5     QShortcut *shortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_F), this);
 6     connect(shortcut, SIGNAL(activated()), this, SLOT(slotSpeedSearch()));
 7 
 8     void MainWindow::slotSpeedSearch()
 9     {
10         m_speedSearch->move(100, 50);
11         m_speedSearch->show();
12     }

打开后清空之前的显示并且将焦点设置到编辑框

1 void SpeedSearch::showEvent(QShowEvent *event)
2 {
3     QWidget::showEvent(event);
4     m_comboBox->setCurrentText("");
5     m_comboBox->setFocus();
6 }

数据初始化

 1 void SpeedSearch::initData(const QStringList &strList)
 2 {
 3     if (m_completer) {
 4         delete m_completer;
 5     }
 6     m_completer = new QCompleter(strList, this);
 7     m_completer->setFilterMode(Qt::MatchContains);
 8     m_comboBox->setCompleter(m_completer);
 9     m_comboBox->clear();
10     m_comboBox->addItems(strList);
11 }

匹配规则设置为contains否则从第一个字符开始匹配,中间的匹配不了。给ComboBox也初始化数据这样点击弹出按钮后列表框也有数据

speed_search.h

 1 #pragma once
 2 
 3 #include <QWidget>
 4 
 5 class QComboBox;
 6 class QCompleter;
 7 class SpeedSearch : public QWidget
 8 {
 9     Q_OBJECT
10 public:
11     explicit SpeedSearch(QWidget *parent = 0);
12     void initData(const QStringList &strList);
13 
14 public slots:
15     void slotCurrentIndexChanged(const QString &str);
16 
17 protected:
18     void showEvent(QShowEvent *event);
19 
20 private:
21     QComboBox *m_comboBox;
22     QCompleter *m_completer;
23 };

speed_search.cpp

 1 #include "speed_search.h"
 2 #include <QtWidgets>
 3 
 4 SpeedSearch::SpeedSearch(QWidget *parent)
 5     : QWidget(parent)
 6     , m_completer(nullptr)
 7 {
 8     m_comboBox = new QComboBox(this);
 9     m_comboBox->setEditable(true);
10     connect(m_comboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotCurrentIndexChanged(QString)));
11 
12     QVBoxLayout *vLayout = new QVBoxLayout(this);
13     vLayout->setContentsMargins(0, 0, 0, 0);
14     vLayout->setSpacing(0);
15     vLayout->addWidget(m_comboBox);
16 
17     this->setFixedSize(150, 24);
18 }
19 
20 void SpeedSearch::initData(const QStringList &strList)
21 {
22     if (m_completer) {
23         delete m_completer;
24     }
25     m_completer = new QCompleter(strList, this);
26     m_completer->setFilterMode(Qt::MatchContains);
27     m_comboBox->setCompleter(m_completer);
28     m_comboBox->clear();
29     m_comboBox->addItems(strList);
30 }
31 
32 void SpeedSearch::slotCurrentIndexChanged(const QString &str)
33 {
34     qDebug() << str;
35     hide();
36 }
37 
38 void SpeedSearch::showEvent(QShowEvent *event)
39 {
40     QWidget::showEvent(event);
41     m_comboBox->setCurrentText("");
42     m_comboBox->setFocus();
43 }
原文地址:https://www.cnblogs.com/ybqjymy/p/14377813.html