qt中使用QCompleter实现查找功能

引言

本文有两个例子,示例一中通过在combox中输入文本可以实现自动补全,用户根据提示列表,选中某一个信息,作为要搜索的字符串。示例二中用户输入要搜索的文本在行编辑器中,当输入的文本在搜索的字符串列表中时,会出现相应的提示列表,用户可选择提示列表中的字符串。示例二没有搜索按钮,只是简单的根据输入的字符串可以检索到被搜索的列表中的字符串。

示例

项目的结构
在这里插入图片描述
示例一和示例二在同一个工程下,没有只是用两个函数区分开了,一个是下拉列表的搜索功能,一个是行编辑器的搜索功能。下面看具体的实现。
代码部分:
main.cpp

#include "dialog.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();
    return a.exec();
}

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>

/********************************************
        ======功能描述:=======
        1.根据输入的字符串进行匹配查找。
        注意:
        Qt::MatchStartsWith----匹配开头
        Qt::MatchEndsWith----匹配结尾
        Qt::MatchContains----匹配内容
********************************************/

QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE

class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();
protected:
    void initCombox();//初始化combox
    void initLineEdit();//初始化行编辑器
private slots:
    void on_searchBtn_clicked();//搜索按钮

private:
    Ui::Dialog *ui;
};
#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include <QCompleter>
#include <QDebug>

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);

    initCombox();
    initLineEdit();
}

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

void Dialog::initCombox()
{
    QStringList strList;
    strList<<QStringLiteral("开始")<<"ejis"<<QStringLiteral("及深度")<<QStringLiteral("随时")<<QStringLiteral("技术的")<<"sdsf";
    ui->comboBox->addItems(strList);
    ui->comboBox->setCurrentText("");
    ui->comboBox->setEditable(true);

    QCompleter *completer = new QCompleter(strList,this);
    completer->setFilterMode(Qt::MatchContains);//匹配内容
    ui->comboBox->setCompleter(completer);
}

void Dialog::initLineEdit()
{
    QStringList strList;
    strList<<QStringLiteral("开始")<<"ejis"<<QStringLiteral("及深度")<<QStringLiteral("随时")<<QStringLiteral("技术的")<<"sdsf";

    QCompleter *completer = new QCompleter(strList,this);
    completer->setFilterMode(Qt::MatchContains);//匹配内容

    ui->lineEdit->setCompleter(completer);
}


void Dialog::on_searchBtn_clicked()
{
    qDebug()<<QStringLiteral("被搜索的字符串是:")<<ui->comboBox->currentText();
}

ui文件中的结构
在这里插入图片描述
程序运行的结果:
在这里插入图片描述以上便是搜索功能,但是值得注意的是:
设置搜索的类型,
Qt::MatchStartsWith----匹配开头
Qt::MatchEndsWith----匹配结尾
Qt::MatchContains----匹配内容
在函数setFilterMode中设置不同的参数会有不同的结果。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肩上风骋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值