Custom Sort/Filter Model Example¶
The Custom Sort/Filter Model example illustrates how to subclass
QSortFilterProxyModel
to perform advanced sorting and filtering.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 theWindow
class to see how the model is used. Finally we will take a quick look at themain()
function.
MySortFilterProxyModel Class Definition¶
The
MySortFilterProxyModel
class inherits theQSortFilterProxyModel
class.Since
QAbstractProxyModel
and its subclasses are derived fromQAbstractItemModel
, 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 theQSortFilterProxyModel
class to ensure that our filter can recognize a valid range of dates, and to control the sorting behavior.class MySortFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT public: MySortFilterProxyModel(QObject *parent = 0); QDate filterMinimumDate() const { return minDate; } void setFilterMinimumDate(QDate date); QDate filterMaximumDate() const { return maxDate; } void setFilterMaximumDate(QDate date); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; private: bool dateInRange(QDate date) const; QDate minDate; QDate maxDate; };We want to be able to filter our data by specifying a given period of time. For that reason, we implement the custom
setFilterMinimumDate()
andsetFilterMaximumDate()
functions as well as the correspondingfilterMinimumDate()
andfilterMaximumDate()
functions. We reimplementQSortFilterProxyModel
‘sfilterAcceptsRow()
function to only accept rows with valid dates, andlessThan()
to be able to sort the senders by their email addresses. Finally, we implement adateInRange()
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:def __init__(self, parent): QSortFilterProxyModel.__init__(self, parent)The most interesting parts of the
MySortFilterProxyModel
implementation are the reimplementations ofQSortFilterProxyModel
‘sfilterAcceptsRow()
andlessThan()
functions. Let’s first take a look at our customizedlessThan()
function.def lessThan(self, left, right): leftData = sourceModel().data(left) rightData = sourceModel().data(right)We want to sort the senders by their email addresses. The
lessThan()
function is used as the < operator when sorting. The default implementation handles a collection of types includingQDateTime
and String, but in order to be able to sort the senders by their email addresses we must first identify the address within the given string:if isinstance(leftData, QDateTime): return leftData < rightData else: emailPattern = QRegExp("([\\w\\.]*@[\\w\\.]*)") if left.column() == 1 && emailPattern.indexIn(leftData) != -1: leftData = emailPattern.cap(1) if right.column() == 1 && emailPattern.indexIn(rightData) != -1: rightData = emailPattern.cap(1) return leftString < rightStringWe use
QRegularExpression
to define a pattern for the addresses we are looking for. Thematch()
function returns aQRegularExpressionMatch
object which contains the result of the matching. If there is a match,hasMatch()
returns true. The result of the match can be retrieved withQRegularExpressionMatch
‘scaptured()
function. The entire match has index 0 and the parenthesized subexpressions have indexes starting from 1 (excluding non-capturing parentheses).def filterAcceptsRow(self, sourceRow, sourceParent): index0 = sourceModel().index(sourceRow, 0, sourceParent) index1 = sourceModel().index(sourceRow, 1, sourceParent) index2 = sourceModel().index(sourceRow, 2, sourceParent) regex = filterRegExp() return (regex.indexIn(sourceModel().data(index0)) != -1 or regex.indexIn(sourceModel().data(index1)) != -1 and dateInRange(sourceModel().data(index2))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.def dateInRange(self, date): return (!minDate.isValid() || date > minDate) && (!maxDate.isValid() || date < maxDate)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:
def setFilterMinimumDate(self, date): self.minDate = date self.invalidateFilter() def setFilterMaximumDate(self, date): self.maxDate = date self.invalidateFilter()The get functions,
filterMinimumDate()
andfilterMaximumDate()
, 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 inheritsQWidget
, and provides this example’s main application window:class Window : public QWidget { Q_OBJECT public: Window(); void setSourceModel(QAbstractItemModel *model); private slots: void textFilterChanged(); void dateFilterChanged(); private: MySortFilterProxyModel *proxyModel; QGroupBox *sourceGroupBox; QGroupBox *proxyGroupBox; QTreeView *sourceView; QTreeView *proxyView; QLabel *filterPatternLabel; QLabel *fromLabel; QLabel *toLabel; FilterWidget *filterWidget; QDateEdit *fromDateEdit; QDateEdit *toDateEdit; };We implement two private slots,
textFilterChanged()
anddateFilterChanged()
, to respond to the user changing the filter pattern, case sensitivity, or any of the dates. In addition, we implement a publicsetSourceModel()
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:Window::Window() { proxyModel = new MySortFilterProxyModel(this);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:
sourceView = new QTreeView; sourceView->setRootIsDecorated(false); 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.sourceLayout->addWidget(sourceView); sourceGroupBox = new QGroupBox(tr("Original Model")); 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:
filterWidget = new FilterWidget; filterWidget->setText(tr("Grace|Sports")); connect(filterWidget, &FilterWidget::filterChanged, this, &Window::textFilterChanged); filterPatternLabel = new QLabel(tr("&Filter pattern:")); filterPatternLabel->setBuddy(filterWidget); fromDateEdit = new QDateEdit; fromDateEdit->setDate(QDate(1970, 01, 01)); fromLabel = new QLabel(tr("F&rom:")); fromLabel->setBuddy(fromDateEdit); toDateEdit = new QDateEdit; toDateEdit->setDate(QDate(2099, 12, 31)); toLabel = new QLabel(tr("&To:")); toLabel->setBuddy(toDateEdit); connect(filterWidget, &QLineEdit::textChanged, this, &Window::textFilterChanged); connect(fromDateEdit, &QDateTimeEdit::dateChanged, this, &Window::dateFilterChanged); connect(toDateEdit, &QDateTimeEdit::dateChanged, this, &Window::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.
proxyView = new QTreeView; proxyView->setRootIsDecorated(false); proxyView->setAlternatingRowColors(true); proxyView->setModel(proxyModel); proxyView->setSortingEnabled(true); proxyView->sortByColumn(1, Qt::AscendingOrder); QGridLayout *proxyLayout = new QGridLayout; proxyLayout->addWidget(proxyView, 0, 0, 1, 3); proxyLayout->addWidget(filterPatternLabel, 1, 0); proxyLayout->addWidget(filterWidget, 1, 1); proxyLayout->addWidget(fromLabel, 3, 0); proxyLayout->addWidget(fromDateEdit, 3, 1, 1, 2); proxyLayout->addWidget(toLabel, 4, 0); proxyLayout->addWidget(toDateEdit, 4, 1, 1, 2); proxyGroupBox = new QGroupBox(tr("Sorted/Filtered Model")); 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
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.QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(sourceGroupBox); mainLayout->addWidget(proxyGroupBox); setLayout(mainLayout); setWindowTitle(tr("Custom Sort/Filter Model")); resize(500, 450); }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 theWindow::setSourceModel()
function to make the application use it:void Window::setSourceModel(QAbstractItemModel *model) { proxyModel->setSourceModel(model); sourceView->setModel(model); for (int i = 0; i < proxyModel->columnCount(); ++i) proxyView->resizeColumnToContents(i); for (int i = 0; i < model->columnCount(); ++i) sourceView->resizeColumnToContents(i); }The
setSourceModel()
function makes the proxy model process the data in the given model, in this case out mail model. ThesetModel()
that the view widget inherits from theQAbstractItemModel
class, sets the model for the view to present. Note that the latter function will also create and set a new selection model.void Window::textFilterChanged() { QRegExp regExp(filterWidget->text(), filterWidget->caseSensitivity(), filterWidget->patternSyntax()); proxyModel->setFilterRegExp(regExp); }The
textFilterChanged()
function is called whenever the user changes the filter pattern or the case sensitivity.We first retrieve the preferred syntax (the
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’sfilterRegExp
property. ThefilterRegExp
property holds the regular expression used to filter the contents of the source model. Note that callingQSortFilterProxyModel
‘ssetFilterRegExp()
function also updates the model.void Window::dateFilterChanged() { proxyModel->setFilterMinimumDate(fromDateEdit->date()); proxyModel->setFilterMaximumDate(toDateEdit->date()); }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:int main(int argc, char *argv[]) { QApplication app(argc, argv); Window window; window.setSourceModel(createMailModel(&window)); window.show(); return app.exec(); }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 theQStandardItemModel
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 usingaddMail()
, another convenience function. Seeitemviews/customsortfiltermodel/main.cpp
for details.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.