Custom Sort/Filter Model Example

Files:

The Custom Sort/Filter Model example illustrates how to subclass QSortFilterProxyModel to perform advanced sorting and filtering.

Screenshot of the Custom Sort/Filter Model Example

Screenshot of the Custom Sort/Filter Model Example

The QSortFilterProxyModel class provides support for sorting and filtering data passed between another model and a view.

The model transforms the structure of a source model by mapping the model indexes it supplies to new indexes, corresponding to different locations, for views to use. This approach allows a given source model to be restructured as far as views are concerned, without requiring any transformations on the underlying data and without duplicating the data in memory.

The Custom Sort/Filter Model example consists of two classes:

  • The MySortFilterProxyModel class provides a custom proxy model.
  • The Window class provides the main application window, using the custom proxy model to sort and filter a standard item model.

We will first take a look at the MySortFilterProxyModel class to see how the custom proxy model is implemented, then we will take a look at the Window class to see how the model is used. Finally we will take a quick look at the main() function.

MySortFilterProxyModel Class Definition

The MySortFilterProxyModel class inherits the QSortFilterProxyModel class.

Since QAbstractProxyModel and its subclasses are derived from QAbstractItemModel, much of the same advice about subclassing normal models also applies to proxy models.

On the other hand, it is worth noting that many of QSortFilterProxyModel's default implementations of functions are written so that they call the equivalent functions in the relevant source model. This simple proxying mechanism may need to be overridden for source models with more complex behavior; in this example we derive from the QSortFilterProxyModel class to ensure that our filter can recognize a valid range of dates, and to control the sorting behavior.

  1. class MySortFilterProxyModel : public QSortFilterProxyModel
  2.  {
  3.     Q_OBJECT
  4.  
  5. public:
  6.     MySortFilterProxyModel(QObject *parent = 0);
  7.  
  8.     QDate filterMinimumDate() const  { return minDate; }
  9.     void setFilterMinimumDate(const QDate &date);
  10.  
  11.     QDate filterMaximumDate() const  { return maxDate; }
  12.     void setFilterMaximumDate(const QDate &date);
  13.  
  14. protected:
  15.     bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
  16.     bool lessThan(const QModelIndex &left, const QModelIndex &right) const;
  17.  
  18. private:
  19.     bool dateInRange(const QDate &date) const;
  20.  
  21.     QDate minDate;
  22.     QDate maxDate;
  23. };

We want to be able to filter our data by specifying a given period of time. For that reason, we implement the custom setFilterMinimumDate() and setFilterMaximumDate() functions as well as the corresponding filterMinimumDate() and filterMaximumDate() functions. We reimplement QSortFilterProxyModel's filterAcceptsRow() function to only accept rows with valid dates, and QSortFilterProxyModel::lessThan() to be able to sort the senders by their email adresses. Finally, we implement a dateInRange() convenience function that we will use to determine if a date is valid.

MySortFilterProxyModel Class Implementation

The MySortFilterProxyModel constructor is trivial, passing the parent parameter on to the base class constructor:

  1. MySortFilterProxyModel::MySortFilterProxyModel(QObject *parent)
  2.     : QSortFilterProxyModel(parent)
  3.  {
  4. }

The most interesting parts of the MySortFilterProxyModel implementation are the reimplementations of QSortFilterProxyModel's filterAcceptsRow() and lessThan() functions. Let's first take a look at our customized lessThan() function.

  1. bool MySortFilterProxyModel::lessThan(const QModelIndex &left,
  2.                                       const QModelIndex &right) const
  3.  {
  4.     QVariant leftData = sourceModel()->data(left);
  5.     QVariant rightData = sourceModel()->data(right);

We want to sort the senders by their email adresses. The lessThan() function is used as the < operator when sorting. The default implementation handles a collection of types including QDateTime and String, but in order to be able to sort the senders by their email adresses we must first identify the adress within the given string:

  1.     if (leftData.type() == QVariant::DateTime)  {
  2.         return leftData.toDateTime() < rightData.toDateTime();
  3.     } else  {
  4.         QRegExp *emailPattern = new QRegExp("([\\w\\.]*@[\\w\\.]*)");
  5.  
  6.         QString leftString = leftData.toString();
  7.         if(left.column() == 1 && emailPattern->indexIn(leftString) != -1)
  8.             leftString = emailPattern->cap(1);
  9.  
  10.         QString rightString = rightData.toString();
  11.         if(right.column() == 1 && emailPattern->indexIn(rightString) != -1)
  12.             rightString = emailPattern->cap(1);
  13.  
  14.         return QString::localeAwareCompare(leftString, rightString) < 0;
  15.     }
  16. }

We use QRegExp to define a pattern for the adresses we are looking for. The QRegExp::indexIn() function attempts to find a match in the given string and returns the position of the first match, or -1 if there was no match. If the given string contains the pattern, we use QRegExp's cap() function to retrieve the actual adress. The cap() function returns the text captured by the nth subexpression. The entire match has index 0 and the parenthesized subexpressions have indexes starting from 1 (excluding non-capturing parentheses).

  1. bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow,
  2.         const QModelIndex &sourceParent) const
  3.  {
  4.     QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
  5.     QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
  6.     QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent);
  7.  
  8.     return (sourceModel()->data(index0).toString().contains(filterRegExp())
  9.             || sourceModel()->data(index1).toString().contains(filterRegExp()))
  10.            && dateInRange(sourceModel()->data(index2).toDate());
  11. }

The filterAcceptsRow() function, on the other hand, is expected to return true if the given row should be included in the model. In our example, a row is accepted if either the subject or the sender contains the given regular expression, and the date is valid.

  1. bool MySortFilterProxyModel::dateInRange(const QDate &date) const
  2.  {
  3.     return (!minDate.isValid() || date > minDate)
  4.            && (!maxDate.isValid() || date < maxDate);
  5. }

We use our custom dateInRange() function to determine if a date is valid.

To be able to filter our data by specifying a given period of time, we also implement functions for getting and setting the minimum and maximum dates:

  1. void MySortFilterProxyModel::setFilterMinimumDate(const QDate &date)
  2.  {
  3.     minDate = date;
  4.     invalidateFilter();
  5. }
  6.  
  7. void MySortFilterProxyModel::setFilterMaximumDate(const QDate &date)
  8.  {
  9.     maxDate = date;
  10.     invalidateFilter();
  11. }

The get functions, filterMinimumDate() and filterMaximumDate(), are trivial and implemented as inline function in the header file.

This completes our custom proxy model. Let's see how we can use it in an application.

Window Class Definition

The CustomFilter class inherits QWidget, and provides this example's main application window:

  1. class Window : public QWidget
  2.  {
  3.     Q_OBJECT
  4.  
  5. public:
  6.     Window();
  7.  
  8.     void setSourceModel(QAbstractItemModel *model);
  9.  
  10. private slots:
  11.     void textFilterChanged();
  12.     void dateFilterChanged();
  13.  
  14. private:
  15.     MySortFilterProxyModel *proxyModel;
  16.  
  17.     QGroupBox *sourceGroupBox;
  18.     QGroupBox *proxyGroupBox;
  19.     QTreeView *sourceView;
  20.     QTreeView *proxyView;
  21.     QCheckBox *filterCaseSensitivityCheckBox;
  22.     QLabel *filterPatternLabel;
  23.     QLabel *fromLabel;
  24.     QLabel *toLabel;
  25.     QLineEdit *filterPatternLineEdit;
  26.     QComboBox *filterSyntaxComboBox;
  27.     QDateEdit *fromDateEdit;
  28.     QDateEdit *toDateEdit;
  29. };

We implement two private slots, textFilterChanged() and dateFilterChanged(), to respond to the user changing the filter pattern, case sensitivity or any of the dates. In addition, we implement a public setSourceModel() convenience function to set up the model/ view relation.

Window Class Implementation

In this example, we have chosen to create and set the source model in the main () function (which we will come back to later). So when constructing the main application window, we assume that a source model already exists and start by creating an instance of our custom proxy model:

  1. Window::Window()
  2.  {
  3.     proxyModel = new MySortFilterProxyModel(this);
  4.     proxyModel->setDynamicSortFilter(true);

We set the dynamicSortFilter property that holds whether the proxy model is dynamically sorted and filtered. By setting this property to true, we ensure that the model is sorted and filtered whenever the contents of the source model change.

The main application window shows views of both the source model and the proxy model. The source view is quite simple:

  1.     sourceView = new QTreeView;
  2.     sourceView->setRootIsDecorated(false);
  3.     sourceView->setAlternatingRowColors(true);

The QTreeView class provides a default model/view implementation of a tree view; our view implements a tree representation of items in the application's source model.

  1.     sourceLayout->addWidget(sourceView);
  2.     sourceGroupBox = new QGroupBox(tr("Original Model"));
  3.     sourceGroupBox->setLayout(sourceLayout);

The QTreeView class provides a default model/view implementation of a tree view; our view implements a tree representation of items in the application's source model. We add our view widget to a layout that we install on a corresponding group box.

The proxy model view, on the other hand, contains several widgets controlling the various aspects of transforming the source model's data structure:

  1.     filterCaseSensitivityCheckBox = new QCheckBox(tr("Case sensitive filter"));
  2.     filterCaseSensitivityCheckBox->setChecked(true);
  3.  
  4.     filterPatternLineEdit = new QLineEdit;
  5.     filterPatternLineEdit->setText("Grace|Sports");
  6.  
  7.     filterPatternLabel = new QLabel(tr("&Filter pattern:"));
  8.     filterPatternLabel->setBuddy(filterPatternLineEdit);
  9.  
  10.     filterSyntaxComboBox = new QComboBox;
  11.     filterSyntaxComboBox->addItem(tr("Regular expression"), QRegExp::RegExp);
  12.     filterSyntaxComboBox->addItem(tr("Wildcard"), QRegExp::Wildcard);
  13.     filterSyntaxComboBox->addItem(tr("Fixed string"), QRegExp::FixedString);
  14.  
  15.     fromDateEdit = new QDateEdit;
  16.     fromDateEdit->setDate(QDate(1970, 01, 01));
  17.     fromLabel = new QLabel(tr("F&rom:"));
  18.     fromLabel->setBuddy(fromDateEdit);
  19.  
  20.     toDateEdit = new QDateEdit;
  21.     toDateEdit->setDate(QDate(2099, 12, 31));
  22.     toLabel = new QLabel(tr("&To:"));
  23.     toLabel->setBuddy(toDateEdit);
  24.  
  25.     connect(filterPatternLineEdit, SIGNAL(textChanged(QString)),
  26.             this, SLOT(textFilterChanged()));
  27.     connect(filterSyntaxComboBox, SIGNAL(currentIndexChanged(int)),
  28.             this, SLOT(textFilterChanged()));
  29.     connect(filterCaseSensitivityCheckBox, SIGNAL(toggled(bool)),
  30.             this, SLOT(textFilterChanged()));
  31.     connect(fromDateEdit, SIGNAL(dateChanged(QDate)),
  32.             this, SLOT(dateFilterChanged()));
  33.     connect(toDateEdit, SIGNAL(dateChanged(QDate)),
  34.             this, SLOT(dateFilterChanged()));

Note that whenever the user changes one of the filtering options, we must explicitly reapply the filter. This is done by connecting the various editors to functions that update the proxy model.

  1.     proxyView = new QTreeView;
  2.     proxyView->setRootIsDecorated(false);
  3.     proxyView->setAlternatingRowColors(true);
  4.     proxyView->setModel(proxyModel);
  5.     proxyView->setSortingEnabled(true);
  6.     proxyView->sortByColumn(1, Qt::AscendingOrder);
  7.  
  8.     QGridLayout *proxyLayout = new QGridLayout;
  9.     proxyLayout->addWidget(proxyView, 0, 0, 1, 3);
  10.     proxyLayout->addWidget(filterPatternLabel, 1, 0);
  11.     proxyLayout->addWidget(filterPatternLineEdit, 1, 1);
  12.     proxyLayout->addWidget(filterSyntaxComboBox, 1, 2);
  13.     proxyLayout->addWidget(filterCaseSensitivityCheckBox, 2, 0, 1, 3);
  14.     proxyLayout->addWidget(fromLabel, 3, 0);
  15.     proxyLayout->addWidget(fromDateEdit, 3, 1, 1, 2);
  16.     proxyLayout->addWidget(toLabel, 4, 0);
  17.     proxyLayout->addWidget(toDateEdit, 4, 1, 1, 2);
  18.  
  19.     proxyGroupBox = new QGroupBox(tr("Sorted/Filtered Model"));
  20.     proxyGroupBox->setLayout(proxyLayout);

The sorting will be handled by the view. All we have to do is to enable sorting for our proxy view by setting the QTreeView::sortingEnabled property (which is false by default). Then we add all the filtering widgets and the proxy view to a layout that we install on a corresponding group box.

  1.     QVBoxLayout *mainLayout = new QVBoxLayout;
  2.     mainLayout->addWidget(sourceGroupBox);
  3.     mainLayout->addWidget(proxyGroupBox);
  4.     setLayout(mainLayout);
  5.  
  6.     setWindowTitle(tr("Custom Sort/Filter Model"));
  7.     resize(500, 450);
  8. }

Finally, after putting our two group boxes into another layout that we install on our main application widget, we customize the application window.

As mentioned above, we create the source model in the main () function, calling the Window::setSourceModel() function to make the application use it:

  1. void Window::setSourceModel(QAbstractItemModel *model)
  2.  {
  3.     proxyModel->setSourceModel(model);
  4.     sourceView->setModel(model);
  5. }

The QSortFilterProxyModel::setSourceModel() function makes the proxy model process the data in the given model, in this case out mail model. The setModel() that the view widget inherits from the QAbstractItemModel class, sets the model for the view to present. Note that the latter function will also create and set a new selection model.

  1. void Window::textFilterChanged()
  2.  {
  3.     QRegExp::PatternSyntax syntax =
  4.             QRegExp::PatternSyntax(filterSyntaxComboBox->itemData(
  5.                     filterSyntaxComboBox->currentIndex()).toInt());
  6.     Qt::CaseSensitivity caseSensitivity =
  7.             filterCaseSensitivityCheckBox->isChecked() ? Qt::CaseSensitive
  8.                                                        : Qt::CaseInsensitive;
  9.  
  10.     QRegExp regExp(filterPatternLineEdit->text(), caseSensitivity, syntax);
  11.     proxyModel->setFilterRegExp(regExp);
  12. }

The textFilterChanged() function is called whenever the user changes the filter pattern or the case sensitivity.

We first retrieve the preferred syntax (the QRegExp::PatternSyntax enum is used to interpret the meaning of the given pattern), then we determine the preferred case sensitivity. Based on these preferences and the current filter pattern, we set the proxy model's filterRegExp property. The filterRegExp property holds the regular expression used to filter the contents of the source model. Note that calling QSortFilterProxyModel's setFilterRegExp() function also updates the model.

  1. void Window::dateFilterChanged()
  2.  {
  3.     proxyModel->setFilterMinimumDate(fromDateEdit->date());
  4.     proxyModel->setFilterMaximumDate(toDateEdit->date());
  5. }

The dateFilterChanged() function is called whenever the user modifies the range of valid dates. We retrieve the new dates from the user interface, and call the corresponding functions (provided by our custom proxy model) to set the proxy model's minimum and maximum dates. As we explained above, calling these functions also updates the model.

The Main() Function

In this example, we have separated the application from the source model by creating the model in the main () function. First we create the application, then we create the source model:

  1. int main(int argc, char *argv[])
  2.  {
  3.     QApplication app(argc, argv);
  4.     Window window;
  5.     window.setSourceModel(createMailModel(&window));
  6.     window.show();
  7.     return app.exec();
  8. }

The createMailModel() function is a convenience function provided to simplify the constructor. All it does is to create and return a model describing a collection of emails. The model is an instance of the QStandardItemModel class, i.e., a generic model for storing custom data typically used as a repository for standard Qt data types. Each mail description is added to the model using addMail(), another convenience function. See main.cpp for details.

Notes provided by the Qt Community

No notes