Qt实现模糊搜索

一、模糊搜索界面由QLineEdit、QCombox组合实现,原始界面如下图所示

  

 二、实现效果如下图所示

    

 三、示例代码

  ① .h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    void FuzzySearch();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

  ② cpp文件

#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QCompleter>
#include <QListView>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    FuzzySearch();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::FuzzySearch()
{
    QStringList wordList;
    wordList << "alpha" << "omega" << "omicron" << "zeta";
    ui->comboBox->addItems(wordList);

    ui->comboBox->setView(new QListView());
    ui->comboBox->setEditable(true);
    ui->comboBox->setLineEdit(ui->lineEdit);
    ui->comboBox->setMaxVisibleItems(5);//下拉列表显示item数

//    QString arrowImagePath = ":/res/combox.png";
//    ui->comboBox->setStyleSheet("QComboBox {font-family: \"Arial\"; font-size: 13px; padding: 3px 0x 3px 5px;}"
//        "QComboBox::drop-down {subcontrol-origin: padding; subcontrol-position: top right; width: 30 px; border: 0px;}"
//        "QComboBox::down-arrow {image: url("+ arrowImagePath +");}");

    ui->comboBox->view()->setStyleSheet("QListView {font-family: \"Arial\"; font-size: 13px; outline: 0px;}"
        "QListView::item {padding: 3px 0x 3px 5px; border-width: 0px;}"
        "QListView::item:selected {background-color: rgb(74, 144, 226);}");

    QCompleter *pCompleter = new QCompleter(wordList, this);
    ui->lineEdit->setCompleter(pCompleter);
    pCompleter->setCaseSensitivity(Qt::CaseInsensitive);
    ui->comboBox->setCompleter(pCompleter);

    ui->lineEdit->clear();
}

 

posted on 2019-09-24 15:42  jiangsion  阅读(5486)  评论(0编辑  收藏  举报

导航