QSortFilterProxyModel¶
The
QSortFilterProxyModel
class provides support for sorting and filtering data passed between another model and a view. More…
Synopsis¶
Functions¶
def
dynamicSortFilter
()def
filterCaseSensitivity
()def
filterKeyColumn
()def
filterRegExp
()def
filterRegularExpression
()def
filterRole
()def
invalidateFilter
()def
isRecursiveFilteringEnabled
()def
isSortLocaleAware
()def
setDynamicSortFilter
(enable)def
setFilterCaseSensitivity
(cs)def
setFilterKeyColumn
(column)def
setFilterRole
(role)def
setRecursiveFilteringEnabled
(recursive)def
setSortCaseSensitivity
(cs)def
setSortLocaleAware
(on)def
setSortRole
(role)def
sortCaseSensitivity
()def
sortColumn
()def
sortOrder
()def
sortRole
()
Virtual functions¶
def
filterAcceptsColumn
(source_column, source_parent)def
filterAcceptsRow
(source_row, source_parent)def
lessThan
(source_left, source_right)
Slots¶
def
invalidate
()def
setFilterFixedString
(pattern)def
setFilterRegExp
(pattern)def
setFilterRegExp
(regExp)def
setFilterRegularExpression
(pattern)def
setFilterRegularExpression
(regularExpression)def
setFilterWildcard
(pattern)
Detailed Description¶
QSortFilterProxyModel
can be used for sorting items, filtering out items, or both. 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.Let’s assume that we want to sort and filter the items provided by a custom model. The code to set up the model and the view, without sorting and filtering, would look like this:
treeView = QTreeView() model = MyItemModel(self) treeView.setModel(model)To add sorting and filtering support to
MyItemModel
, we need to create aQSortFilterProxyModel
, callsetSourceModel()
with theMyItemModel
as argument, and install theQSortFilterProxyModel
on the view:treeView = QTreeView() sourceModel = MyItemModel(self) proxyModel = QSortFilterProxyModel(self) proxyModel.setSourceModel(sourceModel) treeView.setModel(proxyModel)At this point, neither sorting nor filtering is enabled; the original data is displayed in the view. Any changes made through the
QSortFilterProxyModel
are applied to the original model.The
QSortFilterProxyModel
acts as a wrapper for the original model. If you need to convert sourceQModelIndex
es to sorted/filtered model indexes or vice versa, usemapToSource()
,mapFromSource()
,mapSelectionToSource()
, andmapSelectionFromSource()
.Note
By default, the model dynamically re-sorts and re-filters data whenever the original model changes. This behavior can be changed by setting the
dynamicSortFilter
property.The Basic Sort/Filter Model and Custom Sort/Filter Model examples illustrate how to use
QSortFilterProxyModel
to perform basic sorting and filtering and how to subclass it to implement custom behavior.
Sorting¶
QTableView
andQTreeView
have asortingEnabled
property that controls whether the user can sort the view by clicking the view’s horizontal header. For example:treeView.setSortingEnabled(True)When this feature is on (the default is off), clicking on a header section sorts the items according to that column. By clicking repeatedly, the user can alternate between ascending and descending order.
Behind the scene, the view calls the
sort()
virtual function on the model to reorder the data in the model. To make your data sortable, you can either implementsort()
in your model, or use aQSortFilterProxyModel
to wrap your model –QSortFilterProxyModel
provides a genericsort()
reimplementation that operates on thesortRole()
(DisplayRole
by default) of the items and that understands several data types, includingint
,QString
, andQDateTime
. For hierarchical models, sorting is applied recursively to all child items. String comparisons are case sensitive by default; this can be changed by setting thesortCaseSensitivity
property.Custom sorting behavior is achieved by subclassing
QSortFilterProxyModel
and reimplementinglessThan()
, which is used to compare items. For example:bool MySortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { QVariant leftData = sourceModel()->data(left); QVariant rightData = sourceModel()->data(right); if (leftData.type() == QVariant::DateTime) { return leftData.toDateTime() < rightData.toDateTime(); } else { static const QRegularExpression emailPattern("[\\w\\.]*@[\\w\\.]*"); QString leftString = leftData.toString(); if (left.column() == 1) { const QRegularExpressionMatch match = emailPattern.match(leftString); if (match.hasMatch()) leftString = match.captured(0); } QString rightString = rightData.toString(); if (right.column() == 1) { const QRegularExpressionMatch match = emailPattern.match(rightString); if (match.hasMatch()) rightString = match.captured(0); } return QString::localeAwareCompare(leftString, rightString) < 0; } }(This code snippet comes from the Custom Sort/Filter Model example.)
An alternative approach to sorting is to disable sorting on the view and to impose a certain order to the user. This is done by explicitly calling
sort()
with the desired column and order as arguments on theQSortFilterProxyModel
(or on the original model if it implementssort()
). For example:proxyModel.sort(2, Qt.AscendingOrder)
QSortFilterProxyModel
can be sorted by column -1, in which case it returns to the sort order of the underlying source model.
Filtering¶
In addition to sorting,
QSortFilterProxyModel
can be used to hide items that do not match a certain filter. The filter is specified using aQRegExp
object and is applied to thefilterRole()
(DisplayRole
by default) of each item, for a given column. TheQRegExp
object can be used to match a regular expression, a wildcard pattern, or a fixed string. For example:proxyModel.setFilterRegExp(QRegExp(".png", Qt.CaseInsensitive, QRegExp.FixedString)) proxyModel.setFilterKeyColumn(1)For hierarchical models, the filter is applied recursively to all children. If a parent item doesn’t match the filter, none of its children will be shown.
A common use case is to let the user specify the filter regular expression, wildcard pattern, or fixed string in a
QLineEdit
and to connect thetextChanged()
signal tosetFilterRegularExpression()
,setFilterWildcard()
, orsetFilterFixedString()
to reapply the filter.Custom filtering behavior can be achieved by reimplementing the
filterAcceptsRow()
andfilterAcceptsColumn()
functions. For example (from the Custom Sort/Filter Model example), the following implementation ignores thefilterKeyColumn
property and performs filtering on columns 0, 1, and 2:bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent); QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent); return (sourceModel()->data(index0).toString().contains(filterRegExp()) || sourceModel()->data(index1).toString().contains(filterRegExp())) && dateInRange(sourceModel()->data(index2).toDate()); }(This code snippet comes from the Custom Sort/Filter Model example.)
If you are working with large amounts of filtering and have to invoke
invalidateFilter()
repeatedly, usingreset()
may be more efficient, depending on the implementation of your model. However,reset()
returns the proxy model to its original state, losing selection information, and will cause the proxy model to be repopulated.
Subclassing¶
Since
QAbstractProxyModel
and its subclasses are derived fromQAbstractItemModel
, much of the same advice about subclassing normal models also applies to proxy models. In addition, it is worth noting that many of the default implementations of functions in this class 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; for example, if the source model provides a customhasChildren()
implementation, you should also provide one in the proxy model.Note
Some general guidelines for subclassing models are available in the Model Subclassing Reference .
Note
With Qt 5, regular expression support has been improved through the
QRegularExpression
class.QSortFilterProxyModel
dating back prior to that class creation, it originally supported onlyQRegExp
. Since Qt 5.12,QRegularExpression
APIs have been added. Therefore,QRegExp
APIs should be considered deprecated and theQRegularExpression
version should be used in place.Warning
Don’t mix calls to the getters and setters of different regexp types as this will lead to unexpected results. For maximum compatibility, the original implementation has been kept. Therefore, if, for example, a call to
setFilterRegularExpression
is made followed by another one tosetFilterFixedString
, the first call will setup aQRegularExpression
object to use as filter while the second will setup aQRegExp
in FixedString mode. However, this is an implementation detail that might change in the future.See also
QAbstractProxyModel
QAbstractItemModel
Model/View Programming Basic Sort/Filter Model Example Custom Sort/Filter Model ExampleQIdentityProxyModel
-
class
QSortFilterProxyModel
([parent=None])¶ - param parent
Constructs a sorting filter model with the given
parent
.
-
PySide2.QtCore.QSortFilterProxyModel.
dynamicSortFilter
()¶ - Return type
bool
See also
-
PySide2.QtCore.QSortFilterProxyModel.
filterAcceptsColumn
(source_column, source_parent)¶ - Parameters
source_column –
int
source_parent –
QModelIndex
- Return type
bool
Returns
true
if the item in the column indicated by the givensource_column
andsource_parent
should be included in the model; otherwise returnsfalse
.The default implementation returns
true
if the value held by the relevant item matches the filter string, wildcard string or regular expression.Note
By default, the
DisplayRole
is used to determine if the column should be accepted or not. This can be changed by setting thefilterRole
property.
-
PySide2.QtCore.QSortFilterProxyModel.
filterAcceptsRow
(source_row, source_parent)¶ - Parameters
source_row –
int
source_parent –
QModelIndex
- Return type
bool
Returns
true
if the item in the row indicated by the givensource_row
andsource_parent
should be included in the model; otherwise returns false.The default implementation returns
true
if the value held by the relevant item matches the filter string, wildcard string or regular expression.Note
By default, the
DisplayRole
is used to determine if the row should be accepted or not. This can be changed by setting thefilterRole
property.
-
PySide2.QtCore.QSortFilterProxyModel.
filterCaseSensitivity
()¶ - Return type
CaseSensitivity
See also
-
PySide2.QtCore.QSortFilterProxyModel.
filterKeyColumn
()¶ - Return type
int
See also
-
PySide2.QtCore.QSortFilterProxyModel.
filterRegExp
()¶ - Return type
See also
-
PySide2.QtCore.QSortFilterProxyModel.
filterRegularExpression
()¶ - Return type
See also
-
PySide2.QtCore.QSortFilterProxyModel.
filterRole
()¶ - Return type
int
See also
-
PySide2.QtCore.QSortFilterProxyModel.
invalidate
()¶ Invalidates the current sorting and filtering.
See also
-
PySide2.QtCore.QSortFilterProxyModel.
invalidateFilter
()¶ Invalidates the current filtering.
This function should be called if you are implementing custom filtering (e.g.
filterAcceptsRow()
), and your filter parameters have changed.See also
-
PySide2.QtCore.QSortFilterProxyModel.
isRecursiveFilteringEnabled
()¶ - Return type
bool
-
PySide2.QtCore.QSortFilterProxyModel.
isSortLocaleAware
()¶ - Return type
bool
-
PySide2.QtCore.QSortFilterProxyModel.
lessThan
(source_left, source_right)¶ - Parameters
source_left –
QModelIndex
source_right –
QModelIndex
- Return type
bool
Returns
true
if the value of the item referred to by the given indexsource_left
is less than the value of the item referred to by the given indexsource_right
, otherwise returnsfalse
.This function is used as the < operator when sorting, and handles the following
QVariant
types:Int
UInt
LongLong
ULongLong
Float
Double
QChar
QDate
QTime
QDateTime
QString
Any other type will be converted to a
QString
usingtoString()
.Comparison of
QString
s is case sensitive by default; this can be changed using thesortCaseSensitivity
property.By default, the
DisplayRole
associated with theQModelIndex
es is used for comparisons. This can be changed by setting thesortRole
property.Note
The indices passed in correspond to the source model.
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setDynamicSortFilter
(enable)¶ - Parameters
enable –
bool
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterCaseSensitivity
(cs)¶ - Parameters
cs –
CaseSensitivity
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterFixedString
(pattern)¶ - Parameters
pattern – unicode
Sets the fixed string used to filter the contents of the source model to the given
pattern
.
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterKeyColumn
(column)¶ - Parameters
column –
int
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterRegExp
(pattern) - Parameters
pattern – unicode
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterRegularExpression
(regularExpression)¶ - Parameters
regularExpression –
QRegularExpression
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterRegularExpression
(pattern) - Parameters
pattern – unicode
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterRole
(role)¶ - Parameters
role –
int
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setFilterWildcard
(pattern)¶ - Parameters
pattern – unicode
Sets the wildcard expression used to filter the contents of the source model to the given
pattern
.
-
PySide2.QtCore.QSortFilterProxyModel.
setRecursiveFilteringEnabled
(recursive)¶ - Parameters
recursive –
bool
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setSortCaseSensitivity
(cs)¶ - Parameters
cs –
CaseSensitivity
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setSortLocaleAware
(on)¶ - Parameters
on –
bool
See also
-
PySide2.QtCore.QSortFilterProxyModel.
setSortRole
(role)¶ - Parameters
role –
int
See also
-
PySide2.QtCore.QSortFilterProxyModel.
sortCaseSensitivity
()¶ - Return type
CaseSensitivity
See also
-
PySide2.QtCore.QSortFilterProxyModel.
sortColumn
()¶ - Return type
int
the column currently used for sorting
This returns the most recently used sort column.
-
PySide2.QtCore.QSortFilterProxyModel.
sortOrder
()¶ - Return type
SortOrder
the order currently used for sorting
This returns the most recently used sort order.
-
PySide2.QtCore.QSortFilterProxyModel.
sortRole
()¶ - Return type
int
See also
© 2018 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.