QSortFilterProxyModel

详细描述

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 ,调用 PySide.QtGui.QSortFilterProxyModel.setSourceModel() 采用 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.

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() ,和 PySide.QtGui.QSortFilterProxyModel.mapSelectionFromSource() .

注意

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() 特性。

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.

排序

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 ,和 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() 特性。

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() )。例如:

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.

过滤

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() ,或 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.

子类化

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.

注意

Some general guidelines for subclassing models are available in the 模型子类化参考 .

另请参阅

PySide.QtGui.QAbstractProxyModel PySide.QtCore.QAbstractItemModel 模型/视图编程 基本排序/过滤模型范例 自定义排序/过滤模型范例 QIdentityProxyModel

class PySide.QtGui. QSortFilterProxyModel ( [ parent=None ] )
参数: parent PySide.QtCore.QObject

Constructs a sorting filter model with the given parent .

PySide.QtGui.QSortFilterProxyModel. dynamicSortFilter ( )
返回类型: 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 .

默认值为 false。

PySide.QtGui.QSortFilterProxyModel. filterAcceptsColumn ( source_column , source_parent )
参数:
返回类型:

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.

注意

默认情况下, 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() 特性。

PySide.QtGui.QSortFilterProxyModel. filterAcceptsRow ( source_row , source_parent )
参数:
返回类型:

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.

注意

默认情况下, 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() 特性。

PySide.QtGui.QSortFilterProxyModel. filterCaseSensitivity ( )
返回类型: 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 ( )
返回类型: 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 ( )
返回类型: PySide.QtCore.QRegExp

此特性保持 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.

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

PySide.QtGui.QSortFilterProxyModel. filterRole ( )
返回类型: PySide.QtCore.int

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

默认值为 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 ( )
返回类型: 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 )
参数:
返回类型:

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 ,否则返回 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 使用 QVariant.toString() .

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

默认情况下, Qt.DisplayRole associated with the PySide.QtCore.QModelIndex es is used for comparisons. This can be changed by setting the PySide.QtGui.QSortFilterProxyModel.sortRole() 特性。

注意

The indices passed in correspond to the source model.

PySide.QtGui.QSortFilterProxyModel. setDynamicSortFilter ( enable )
参数: enable 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 .

默认值为 false。

PySide.QtGui.QSortFilterProxyModel. setFilterCaseSensitivity ( cs )
参数: cs 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. setFilterFixedString ( pattern )
参数: pattern – unicode

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

PySide.QtGui.QSortFilterProxyModel. setFilterKeyColumn ( column )
参数: column 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. setFilterRegExp ( pattern )
参数: pattern – unicode

这是重载函数。

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

PySide.QtGui.QSortFilterProxyModel. setFilterRegExp ( regExp )
参数: regExp PySide.QtCore.QRegExp

此特性保持 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.

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

PySide.QtGui.QSortFilterProxyModel. setFilterRole ( role )
参数: role PySide.QtCore.int

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

默认值为 Qt.DisplayRole .

PySide.QtGui.QSortFilterProxyModel. setFilterWildcard ( pattern )
参数: pattern – unicode

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

PySide.QtGui.QSortFilterProxyModel. setSortCaseSensitivity ( cs )
参数: cs 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. setSortLocaleAware ( on )
参数: on 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. setSortRole ( role )
参数: role PySide.QtCore.int

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

默认值为 Qt.DisplayRole .

PySide.QtGui.QSortFilterProxyModel. sortCaseSensitivity ( )
返回类型: 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 ( )
返回类型: PySide.QtCore.int

the column currently used for sorting

This returns the most recently used sort column.

PySide.QtGui.QSortFilterProxyModel. sortOrder ( )
返回类型: PySide.QtCore.Qt.SortOrder

the order currently used for sorting

This returns the most recently used sort order.

PySide.QtGui.QSortFilterProxyModel. sortRole ( )
返回类型: PySide.QtCore.int

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

默认值为 Qt.DisplayRole .