QSortFilterProxyModel实现数据筛选

1)dialogimpl.h

#ifndef DIALOGIMPL_H
#define DIALOGIMPL_H
//
#include <QDialog>
#include "ui_dialog.h"
#include "QListView"
#include "QStringListModel"
#include "QVBoxLayout"
#include "QSortFilterProxyModel"
#include "QLabel"
#include "QLineEdit"
#include "QComboBox"
#include "QMessageBox"
//
class DialogImpl : public QDialog, public Ui::Dialog
{
Q_OBJECT
public:
 DialogImpl( QWidget * parent = 0, Qt::WFlags f = 0 );
private slots:
 void filterChanged(QString text);
private:
 QVBoxLayout *mainLayout;
 QListView *view;
 QStringListModel *model;
 QSortFilterProxyModel *modelproxy;
 QComboBox *syntaxbox;
};
#endif

 

2)dialogimpl.cpp

#include "dialogimpl.h"
//
DialogImpl::DialogImpl( QWidget * parent, Qt::WFlags f)
 : QDialog(parent, f)
{
 setupUi(this);
 this->setWindowTitle("QsortFilterProxyModel");
 this->setFixedSize(500,400);
 
 model=new QStringListModel;
 //QColor::colorNames() Returns a QStringList containing the color names Qt knows about.
 model->setStringList(QColor::colorNames());
 
 modelproxy=new QSortFilterProxyModel;
 modelproxy->setSourceModel(model);
 //This property holds the column where the key used to filter the contents of the source model is read from.
 modelproxy->setFilterKeyColumn(0);
 
 view=new QListView;
 view->setModel(modelproxy);
 
 QLabel *filterLabel=new QLabel(tr("filter"));
 QLineEdit *filterEdit=new QLineEdit;
 QHBoxLayout *filterLayout=new QHBoxLayout;
 filterLayout->addWidget(filterLabel);
 filterLayout->addWidget(filterEdit);
 
 syntaxbox=new QComboBox;
 //void setSizePolicy ( QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical )
 //QSizePolicy::Expanding means The QComboBox can make use of extra space, so it should get as much space as possible
 //QSizePolicy::Preferred means The QComboBox can be expanded, but there is no advantage to it being larger than sizeHint()
 syntaxbox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
 // pattern matching syntax
 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);
 
 mainLayout=new QVBoxLayout;
 mainLayout->addWidget(view);
 mainLayout->addLayout(filterLayout);
 mainLayout->addLayout(syntaxLayout);
 this->setLayout(mainLayout);
 
 connect(filterEdit,SIGNAL(textChanged(QString)),this,SLOT(filterChanged(QString)));
}
void DialogImpl::filterChanged(QString text)
{
 int index=syntaxbox->currentIndex();
 //1.QRegExp::RegExp   0
 //2.QRegExp::Wildcard  1
 //3.QRegExp::FixedString 2
 int value=syntaxbox->itemData(index).toInt();
 QRegExp::PatternSyntax syntax = QRegExp::PatternSyntax(value);
 QRegExp regExp(text, Qt::CaseInsensitive, syntax);
 modelproxy->setFilterRegExp(regExp);

}
//

 

你可能感兴趣的:(QSortFilterProxyModel实现数据筛选)