QSortFilterProxyModel

Inheritance diagram of QSortFilterProxyModel

Synopsis

Virtual functions

Slots

Detailed Description

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

PySide.QtGui.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 a PySide.QtGui.QSortFilterProxyModel , call PySide.QtGui.QSortFilterProxyModel.setSourceModel() with the MyItemModel as argument, and install the PySide.QtGui.QSortFilterProxyModel 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 PySide.QtGui.QSortFilterProxyModel are applied to the original model.

The PySide.QtGui.QSortFilterProxyModel acts as a wrapper for the original model. If you need to convert source PySide.QtCore.QModelIndex es to sorted/filtered model indexes or vice versa, use PySide.QtGui.QSortFilterProxyModel.mapToSource() , PySide.QtGui.QSortFilterProxyModel.mapFromSource() , PySide.QtGui.QSortFilterProxyModel.mapSelectionToSource() , and PySide.QtGui.QSortFilterProxyModel.mapSelectionFromSource() .

Note

By default, the model does not dynamically re-sort and re-filter data whenever the original model changes. This behavior can be changed by setting the PySide.QtGui.QSortFilterProxyModel.dynamicSortFilter() property.

The Basic Sort/Filter Model and Custom Sort/Filter Model examples illustrate how to use PySide.QtGui.QSortFilterProxyModel to perform basic sorting and filtering and how to subclass it to implement custom behavior.

Sorting

PySide.QtGui.QTableView and PySide.QtGui.QTreeView have a PySide.QtGui.QTreeView.sortingEnabled() 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.

../../_images/qsortfilterproxymodel-sorting.png

Behind the scene, the view calls the PySide.QtGui.QSortFilterProxyModel.sort() virtual function on the model to reorder the data in the model. To make your data sortable, you can either implement PySide.QtGui.QSortFilterProxyModel.sort() in your model, or use a PySide.QtGui.QSortFilterProxyModel to wrap your model – PySide.QtGui.QSortFilterProxyModel provides a generic PySide.QtGui.QSortFilterProxyModel.sort() reimplementation that operates on the PySide.QtGui.QSortFilterProxyModel.sortRole() ( Qt.DisplayRole by default) of the items and that understands several data types, including int , PySide.QtCore.QString , and PySide.QtCore.QDateTime . For hierarchical models, sorting is applied recursively to all child items. String comparisons are case sensitive by default; this can be changed by setting the PySide.QtGui.QSortFilterProxyModel.sortCaseSensitivity() property.

Custom sorting behavior is achieved by subclassing PySide.QtGui.QSortFilterProxyModel and reimplementing PySide.QtGui.QSortFilterProxyModel.lessThan() , which is used to compare items. For example:

def lessThan(self, left, right):
    leftData = sourceModel().data(left)
    rightData = sourceModel().data(right)



    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 < rightString

(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 PySide.QtGui.QSortFilterProxyModel.sort() with the desired column and order as arguments on the PySide.QtGui.QSortFilterProxyModel (or on the original model if it implements PySide.QtGui.QSortFilterProxyModel.sort() ). For example:

proxyModel.sort(2, Qt.AscendingOrder)

PySide.QtGui.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, PySide.QtGui.QSortFilterProxyModel can be used to hide items that do not match a certain filter. The filter is specified using a PySide.QtCore.QRegExp object and is applied to the PySide.QtGui.QSortFilterProxyModel.filterRole() ( Qt.DisplayRole by default) of each item, for a given column. The PySide.QtCore.QRegExp 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 regexp, wildcard pattern, or fixed string in a PySide.QtGui.QLineEdit and to connect the PySide.QtGui.QLineEdit.textChanged() signal to PySide.QtGui.QSortFilterProxyModel.setFilterRegExp() , PySide.QtGui.QSortFilterProxyModel.setFilterWildcard() , or PySide.QtGui.QSortFilterProxyModel.setFilterFixedString() to reapply the filter.

Custom filtering behavior can be achieved by reimplementing the PySide.QtGui.QSortFilterProxyModel.filterAcceptsRow() and PySide.QtGui.QSortFilterProxyModel.filterAcceptsColumn() functions. For example (from the Custom Sort/Filter Model example), the following implementation ignores the PySide.QtGui.QSortFilterProxyModel.filterKeyColumn() property and performs filtering on columns 0, 1, and 2:

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))

(This code snippet comes from the Custom Sort/Filter Model example.)

If you are working with large amounts of filtering and have to invoke PySide.QtGui.QSortFilterProxyModel.invalidateFilter() repeatedly, using PySide.QtCore.QAbstractItemModel.reset() may be more efficient, depending on the implementation of your model. However, PySide.QtCore.QAbstractItemModel.reset() returns the proxy model to its original state, losing selection information, and will cause the proxy model to be repopulated.

Subclassing

Since PySide.QtGui.QAbstractProxyModel and its subclasses are derived from PySide.QtCore.QAbstractItemModel , 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 custom PySide.QtGui.QSortFilterProxyModel.hasChildren() implementation, you should also provide one in the proxy model.

Note

Some general guidelines for subclassing models are available in the Model Subclassing Reference .

See also

PySide.QtGui.QAbstractProxyModel PySide.QtCore.QAbstractItemModel Model/View Programming Basic Sort/Filter Model Example Custom Sort/Filter Model Example

class PySide.QtGui.QSortFilterProxyModel([parent=None])
Parameters:parentPySide.QtCore.QObject

Constructs a sorting filter model with the given parent .

PySide.QtGui.QSortFilterProxyModel.dynamicSortFilter()
Return type:PySide.QtCore.bool

This property holds whether the proxy model is dynamically sorted and filtered whenever the contents of the source model change.

Note that you should not update the source model through the proxy model when PySide.QtGui.QSortFilterProxyModel.dynamicSortFilter() is true. For instance, if you set the proxy model on a PySide.QtGui.QComboBox , then using functions that update the model, e.g., PySide.QtGui.QComboBox.addItem() , will not work as expected. An alternative is to set PySide.QtGui.QSortFilterProxyModel.dynamicSortFilter() to false and call PySide.QtGui.QSortFilterProxyModel.sort() after adding items to the PySide.QtGui.QComboBox .

The default value is false.

PySide.QtGui.QSortFilterProxyModel.filterAcceptsColumn(source_column, source_parent)
Parameters:
Return type:

PySide.QtCore.bool

Returns true if the item in the column indicated by the given source_column and source_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 Qt.DisplayRole is used to determine if the row should be accepted or not. This can be changed by setting the PySide.QtGui.QSortFilterProxyModel.filterRole() property.

PySide.QtGui.QSortFilterProxyModel.filterAcceptsRow(source_row, source_parent)
Parameters:
Return type:

PySide.QtCore.bool

Returns true if the item in the row indicated by the given source_row and source_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 Qt.DisplayRole is used to determine if the row should be accepted or not. This can be changed by setting the PySide.QtGui.QSortFilterProxyModel.filterRole() property.

PySide.QtGui.QSortFilterProxyModel.filterCaseSensitivity()
Return type:PySide.QtCore.Qt.CaseSensitivity

This property holds the case sensitivity of the PySide.QtCore.QRegExp pattern used to filter the contents of the source model.

By default, the filter is case sensitive.

PySide.QtGui.QSortFilterProxyModel.filterKeyColumn()
Return type:PySide.QtCore.int

This property holds the column where the key used to filter the contents of the source model is read from..

The default value is 0. If the value is -1, the keys will be read from all columns.

PySide.QtGui.QSortFilterProxyModel.filterRegExp()
Return type:PySide.QtCore.QRegExp

This property holds the PySide.QtCore.QRegExp used to filter the contents of the source model.

Setting this property overwrites the current PySide.QtGui.QSortFilterProxyModel.filterCaseSensitivity() . By default, the PySide.QtCore.QRegExp is an empty string matching all contents.

If no PySide.QtCore.QRegExp or an empty string is set, everything in the source model will be accepted.

PySide.QtGui.QSortFilterProxyModel.filterRole()
Return type:PySide.QtCore.int

This property holds the item role that is used to query the source model’s data when filtering items.

The default value is Qt.DisplayRole .

PySide.QtGui.QSortFilterProxyModel.invalidate()

Invalidates the current sorting and filtering.

PySide.QtGui.QSortFilterProxyModel.invalidateFilter()

Invalidates the current filtering.

This function should be called if you are implementing custom filtering (e.g. PySide.QtGui.QSortFilterProxyModel.filterAcceptsRow() ), and your filter parameters have changed.

PySide.QtGui.QSortFilterProxyModel.isSortLocaleAware()
Return type:PySide.QtCore.bool

This property holds the local aware setting used for comparing strings when sorting.

By default, sorting is not local aware.

PySide.QtGui.QSortFilterProxyModel.lessThan(left, right)
Parameters:
Return type:

PySide.QtCore.bool

Returns true if the value of the item referred to by the given index left is less than the value of the item referred to by the given index right , otherwise returns false.

This function is used as the < operator when sorting, and handles the following PySide.QtCore.QVariant types:

  • QVariant.Int
  • QVariant.UInt
  • QVariant.LongLong
  • QVariant.ULongLong
  • QVariant.Double
  • QVariant.Char
  • QVariant.Date
  • QVariant.Time
  • QVariant.DateTime
  • QVariant.String

Any other type will be converted to a PySide.QtCore.QString using QVariant.toString() .

Comparison of PySide.QtCore.QString s is case sensitive by default; this can be changed using the PySide.QtGui.QSortFilterProxyModel.sortCaseSensitivity() property.

By default, the Qt.DisplayRole associated with the PySide.QtCore.QModelIndex es is used for comparisons. This can be changed by setting the PySide.QtGui.QSortFilterProxyModel.sortRole() property.

Note

The indices passed in correspond to the source model.

PySide.QtGui.QSortFilterProxyModel.setDynamicSortFilter(enable)
Parameters:enablePySide.QtCore.bool

This property holds whether the proxy model is dynamically sorted and filtered whenever the contents of the source model change.

Note that you should not update the source model through the proxy model when PySide.QtGui.QSortFilterProxyModel.dynamicSortFilter() is true. For instance, if you set the proxy model on a PySide.QtGui.QComboBox , then using functions that update the model, e.g., PySide.QtGui.QComboBox.addItem() , will not work as expected. An alternative is to set PySide.QtGui.QSortFilterProxyModel.dynamicSortFilter() to false and call PySide.QtGui.QSortFilterProxyModel.sort() after adding items to the PySide.QtGui.QComboBox .

The default value is false.

PySide.QtGui.QSortFilterProxyModel.setFilterCaseSensitivity(cs)
Parameters:csPySide.QtCore.Qt.CaseSensitivity

This property holds the case sensitivity of the PySide.QtCore.QRegExp pattern used to filter the contents of the source model.

By default, the filter is case sensitive.

PySide.QtGui.QSortFilterProxyModel.setFilterFixedString(pattern)
Parameters:pattern – unicode

Sets the fixed string used to filter the contents of the source model to the given pattern .

PySide.QtGui.QSortFilterProxyModel.setFilterKeyColumn(column)
Parameters:columnPySide.QtCore.int

This property holds the column where the key used to filter the contents of the source model is read from..

The default value is 0. If the value is -1, the keys will be read from all columns.

PySide.QtGui.QSortFilterProxyModel.setFilterRegExp(regExp)
Parameters:regExpPySide.QtCore.QRegExp

This property holds the PySide.QtCore.QRegExp used to filter the contents of the source model.

Setting this property overwrites the current PySide.QtGui.QSortFilterProxyModel.filterCaseSensitivity() . By default, the PySide.QtCore.QRegExp is an empty string matching all contents.

If no PySide.QtCore.QRegExp or an empty string is set, everything in the source model will be accepted.

PySide.QtGui.QSortFilterProxyModel.setFilterRegExp(pattern)
Parameters:pattern – unicode

This is an overloaded function.

Sets the regular expression used to filter the contents of the source model to pattern .

PySide.QtGui.QSortFilterProxyModel.setFilterRole(role)
Parameters:rolePySide.QtCore.int

This property holds the item role that is used to query the source model’s data when filtering items.

The default value is Qt.DisplayRole .

PySide.QtGui.QSortFilterProxyModel.setFilterWildcard(pattern)
Parameters:pattern – unicode

Sets the wildcard expression used to filter the contents of the source model to the given pattern .

PySide.QtGui.QSortFilterProxyModel.setSortCaseSensitivity(cs)
Parameters:csPySide.QtCore.Qt.CaseSensitivity

This property holds the case sensitivity setting used for comparing strings when sorting.

By default, sorting is case sensitive.

PySide.QtGui.QSortFilterProxyModel.setSortLocaleAware(on)
Parameters:onPySide.QtCore.bool

This property holds the local aware setting used for comparing strings when sorting.

By default, sorting is not local aware.

PySide.QtGui.QSortFilterProxyModel.setSortRole(role)
Parameters:rolePySide.QtCore.int

This property holds the item role that is used to query the source model’s data when sorting items.

The default value is Qt.DisplayRole .

PySide.QtGui.QSortFilterProxyModel.sortCaseSensitivity()
Return type:PySide.QtCore.Qt.CaseSensitivity

This property holds the case sensitivity setting used for comparing strings when sorting.

By default, sorting is case sensitive.

PySide.QtGui.QSortFilterProxyModel.sortColumn()
Return type:PySide.QtCore.int

the column currently used for sorting

This returns the most recently used sort column.

PySide.QtGui.QSortFilterProxyModel.sortOrder()
Return type:PySide.QtCore.Qt.SortOrder

the order currently used for sorting

This returns the most recently used sort order.

PySide.QtGui.QSortFilterProxyModel.sortRole()
Return type:PySide.QtCore.int

This property holds the item role that is used to query the source model’s data when sorting items.

The default value is Qt.DisplayRole .