Qt文档阅读笔记-QCompleter官方解析及实例

QCompleter类提供了模型item的提示功能。

QCompleter可以再Qt的任意控件进行提示,如QLineEdit和QComboBox控件。当用户开始输入一个单词是,QCompleter会进行提示。

 

下面是QCompleter的基本用法:

QStringList wordList;
wordList << "alpha" << "omega" << "omicron" << "zeta";

QLineEdit *lineEdit = new QLineEdit(this);

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

下面是使用QFileSystemModel的另外一个例子:

QCompleter *completer = new QCompleter(this);
completer->setModel(new QDirModel(completer));
lineEdit->setCompleter(completer);

下面是对QCompleter的数据进行遍历

for(int i = 0; completer->setCurrentRow(i); i++)
      qDebug() << completer->currentCompletion() << " is match number " << i;

下面是个小例子:

程序运行截图如下:

Qt文档阅读笔记-QCompleter官方解析及实例_第1张图片

Qt文档阅读笔记-QCompleter官方解析及实例_第2张图片

关键代码:

#include "widget.h"
#include "ui_widget.h"
#include 
#include 
#include 

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

    QStringList wordList;
    wordList << "alpha" << "omega" << "omicron" << "zeta" << "中文" << "中文中文中文中文";
    QCompleter *completer1 = new QCompleter(wordList, this);
    completer1->setCaseSensitivity(Qt::CaseInsensitive);
    ui->lineEdit->setCompleter(completer1);

    QCompleter *completer2 = new QCompleter(this);
    completer2->setModel(new QDirModel(completer2));
    ui->lineEdit_2->setCompleter(completer2);

    for(int i = 0; completer1->setCurrentRow(i); i++){

        qDebug() << completer1->currentCompletion() << " is match number " << i;
    }
}

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

源码打包下载地址:

https://github.com/fengfanchen/Qt/tree/master/CompleterDemo

你可能感兴趣的:(文档阅读笔记,C/C++,Qt,QCompleter,C,C++,Qt,文档阅读)