QSortFilterProxyModel的简单⽤法
参考<<C++ GUI Programming with Qt 4>>中⽂版第⼆版中的例⼦"ColorNamesDialog",简单介绍QSortFilterProxyModel的⽤法,QSortFilterProxyModel不能单独使⽤,它只是⼀个“代理”,真正的数据需要另外的⼀个model提供,⽽且它是⽤来排序和过滤的。
colornamesdialog.h⽂件:
#ifndef COLORNAMESDIALOG_H
#define COLORNAMESDIALOG_H
#include <QtGui/QDialog>
#include <QSortFilterProxyModel>
#include <QStringListModel>
#include <QListView>
#include <QComboBox>
#include <QLineEdit>
class ColorNamesDialog : public QDialog
{
Q_OBJECT
public:
ColorNamesDialog(QWidget *parent = 0);
~ColorNamesDialog();
private slots:
void reapplyFilter();
private:
QSortFilterProxyModel *proxyModel;
QStringListModel *sourceModel;
QListView *listView;
QComboBox *syntaxComboBox;
QLineEdit *filterLineEdit;
};
#endif
colornamesdialog.cpp⽂件:
#include "colornamesdialog.h"
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
ColorNamesDialog::ColorNamesDialog(QWidget *parent)
: QDialog(parent)
{
sourceModel = new QStringListModel(this);
sourceModel->setStringList(QColor::colorNames());
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(sourceModel);
proxyModel->setFilterKeyColumn(0);
listView = new QListView;
listView->setModel(proxyModel);
QLabel *filterLabel = new QLabel("Filter:", this);
filterLabel->setFixedWidth(100);
QLabel *patternLabel = new QLabel("Pattern syntax:", this);
patternLabel->setFixedWidth(100);
filterLineEdit = new QLineEdit(this);
syntaxComboBox = new QComboBox(this);
syntaxComboBox->addItem("Regular expression", QRegExp::RegExp); // QRegExp::RegExp 为 0
syntaxComboBox->addItem("Wildcard", QRegExp::Wildcard); // QRegExp::Wildcard 为 1
syntaxComboBox->addItem("Fixed string", QRegExp::Wildcard); // QRegExp::Wildcard 为 2
QHBoxLayout *filterLayout = new QHBoxLayout;
filterLayout->addWidget(filterLabel);
filterLayout->addWidget(filterLineEdit);
qt listviewQHBoxLayout *patternLayout = new QHBoxLayout;
patternLayout->addWidget(patternLabel);
patternLayout->addWidget(syntaxComboBox);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(listView);
mainLayout->addLayout(filterLayout);
mainLayout->addLayout(patternLayout);
setLayout(mainLayout);
connect(syntaxComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(reapplyFilter())); connect(filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(reapplyFilter()));
}
ColorNamesDialog::~ColorNamesDialog()
{
}
void ColorNamesDialog::reapplyFilter()
{
QRegExp::PatternSyntax syntax = QRegExp::PatternSyntax(syntaxComboBox->itemData( syntaxComboBox->currentIndex()).toInt());
QRegExp regExp(filterLineEdit->text(), Qt::CaseInsensitive, syntax);
proxyModel->setFilterRegExp(regExp);
}
main.cpp⽂件:
#include <QtGui/QApplication>
#include "colornamesdialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ColorNamesDialog w;
w.show();
w.setWindowTitle("QSortFilterProxyModel Demo");
();
}
运⾏界⾯:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论