Qt QSortFilterProxyModel示例代码, 使用方法

1. QSortFilterProxyModel不能单独使用,它只是一个“代理”,真正的数据需要另外的一个model提供,而且它是用来排序和过滤的。

 

2. 实现代码

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QtGui>

class Dialog : public QDialog
{
    Q_OBJECT
    
public:
    Dialog(QWidget *parent = 0);

public slots:
    void reapplyFilter();

private:
    QSortFilterProxyModel *proxyModel;
    QStringListModel *sourceModel;
    QListView *listView;
    QComboBox *syntaxComboBox;
    QLineEdit *filterLineEdit;
};

#endif // DIALOG_H


dialog.cpp

 

#include "dialog.h"

Dialog::Dialog(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);
    syntaxComboBox->addItem("Wildcard", QRegExp::Wildcard);
    syntaxComboBox->addItem("Fixed string", QRegExp::Wildcard);

    QHBoxLayout *filterLayout = new QHBoxLayout;
    filterLayout->addWidget(filterLabel);
    filterLayout->addWidget(filterLineEdit);
    QHBoxLayout *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()));
}

void Dialog::reapplyFilter()
{
    QRegExp::PatternSyntax syntax = QRegExp::PatternSyntax(syntaxComboBox->itemData(
                                    syntaxComboBox->currentIndex()).toInt());
    QRegExp regExp(filterLineEdit->text(), Qt::CaseInsensitive, syntax);
    proxyModel->setFilterRegExp(regExp);
}


 

 

posted @ 2013-08-20 15:26  今晚打酱油_  阅读(586)  评论(0编辑  收藏  举报