Change QSortFilterProxyModel behaviour for multiple column filtering

前端 未结 3 1493
遥遥无期
遥遥无期 2021-01-03 00:55

We have a QSortFilterProxyModel installed on a QTableView and two (or more) QLineEdit for filtering the view (based on the text of the

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 01:18

    Based on @Hayt's answer and comment. Since you want to have two separate filters on your model, You can have two chained QSortFilterProxyModel(one does the filtering based on the name, and the other does the filtering based on the year using the first filtering model as the source model).

    Here is a fully working example on how to have two separate filters for one table:

    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        //set up GUI
        QWidget w;
        QVBoxLayout layout(&w);
        QHBoxLayout hLayout;
        QLineEdit lineEditName;
        QLineEdit lineEditYear;
        lineEditName.setPlaceholderText("name filter");
        lineEditYear.setPlaceholderText("year filter");
        lineEditYear.setValidator(new QRegExpValidator(QRegExp("[0-9]*")));
        lineEditYear.setMaxLength(4);
        hLayout.addWidget(&lineEditName);
        hLayout.addWidget(&lineEditYear);
    
        QTableView tableView;
        layout.addLayout(&hLayout);
        layout.addWidget(&tableView);
    
        //set up models
        QStandardItemModel sourceModel;
        QSortFilterProxyModel yearFilterModel;
        yearFilterModel.setSourceModel(&sourceModel);
        QSortFilterProxyModel nameFilterModel;
        //nameFilterModel uses yearFilterModel as source
        nameFilterModel.setSourceModel(&yearFilterModel);
        //tableView displayes the last model in the chain nameFilterModel
        tableView.setModel(&nameFilterModel);
        nameFilterModel.setFilterKeyColumn(0);
        yearFilterModel.setFilterKeyColumn(1);
        nameFilterModel.setFilterCaseSensitivity(Qt::CaseInsensitive);
        yearFilterModel.setFilterCaseSensitivity(Qt::CaseInsensitive);
    
        QObject::connect(&lineEditName, &QLineEdit::textChanged, &nameFilterModel,
                static_cast
                (&QSortFilterProxyModel::setFilterRegExp));
        QObject::connect(&lineEditYear, &QLineEdit::textChanged, &yearFilterModel,
                static_cast
                (&QSortFilterProxyModel::setFilterRegExp));
    
        //fill with dummy data
        QVector names{"Danny", "Christine", "Lars",
                               "Roberto", "Maria"};
        for(int i=0; i<100; i++){
            QList row;
            row.append(new QStandardItem(names[i%names.size()]));
            row.append(new QStandardItem(QString::number((i%9)+1980)));
            sourceModel.appendRow(row);
        }
        w.show();
        return a.exec();
    }
    

提交回复
热议问题