- 论坛徽章:
- 49
|
t为我们预定义了很多model,前面已经说过了QStringListModel、QDirModel(也算是Qt推荐使用的 QFileSystemModel吧,这个在上一章最后重新加上了一段话,没有注意的朋友去看看哦)。今天我们要说的这个 QSortFilterProxyModel并不能单独使用,看它的名字就会知道,它只是一个“代理”,真正的数据需要另外的一个model提供,并且它是用来排序和过滤的。所谓过滤,也就是说按照你输入的内容进行数据的筛选,很像Excel里面的过滤器。不过Qt提供的过滤功能是基于正则表达式的,因而功能强大。
我们从代码开始看起:
sortview.h
#ifndef SORTVIEW_H
#define SORTVIEW_H
#include
class SortView : public QWidget
{
Q_OBJECT
public:
SortView();
private:
QListView *view;
QStringListModel *model;
QSortFilterProxyModel *modelProxy;
QComboBox *syntaxBox;
private slots:
void filterChanged(QString text);
};
#endif // SORTVIEW_H
sortview.cpp
#include "sortview.h"
SortView::SortView()
{
model = new QStringListModel(QColor::colorNames(), this);
modelProxy = new QSortFilterProxyModel(this);
modelProxy->setSourceModel(model);
modelProxy->setFilterKeyColumn(0);
view = new QListView(this);
view->setModel(modelProxy);
QLineEdit *filterInput = new QLineEdit;
QLabel *filterLabel = new QLabel(tr("Filter"));
QHBoxLayout *filterLayout = new QHBoxLayout;
filterLayout->addWidget(filterLabel);
filterLayout->addWidget(filterInput);
syntaxBox = new QComboBox;
syntaxBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
syntaxBox->addItem(tr("Regular expression"), QRegExp::RegExp);
syntaxBox->addItem(tr("Wildcard"), QRegExp::Wildcard);
syntaxBox->addItem(tr("Fixed string"), QRegExp::FixedString);
QLabel *syntaxLabel = new QLabel(tr("Syntax"));
QHBoxLayout *syntaxLayout = new QHBoxLayout;
syntaxLayout->addWidget(syntaxLabel);
syntaxLayout->addWidget(syntaxBox);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(view);
layout->addLayout(filterLayout);
layout->addLayout(syntaxLayout);
connect(filterInput, SIGNAL(textChanged(QString)), this, SLOT(filterChanged(QString)));
}
void SortView::filterChanged(QString text)
{
QRegExp::PatternSyntax syntax = QRegExp::PatternSyntax(
syntaxBox->itemData(syntaxBox->currentIndex()).toInt());
QRegExp regExp(text, Qt::CaseInsensitive, syntax);
modelProxy->setFilterRegExp(regExp);
}
编缉推荐阅读以下文章
- Qt学习之路(47): 自定义Model之三
- Qt学习之路(46): 自定义model之二
- Qt学习之路(45): 自定义model之一
- Qt学习之路(43): QDirModel
- Qt学习之路(42): QStringListModel
- Qt学习之路(41): QTableWidget
- Qt学习之路(40): QTreeWidget
- Qt学习之路(39): QListWidget
- Qt学习之路(38): model-view架构
- Qt学习之路(37): Qt容器类之关联存储容器
|
|