QSortFilterProxyModel Class Reference

[ QtGui module]

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

继承 QAbstractProxyModel .

方法


详细描述

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

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:

         QTreeView *treeView = new QTreeView;
         MyItemModel *model = new MyItemModel(this);
         treeView->setModel(model);
			

To add sorting and filtering support to MyItemModel , we need to create a QSortFilterProxyModel, call setSourceModel () 采用 MyItemModel as argument, and install the QSortFilterProxyModel on the view:

         QTreeView *treeView = new QTreeView;
         MyItemModel *sourceModel = new MyItemModel(this);
         QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
         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 source QModelIndex es to sorted/filtered model indexes or vice versa, use mapToSource (), mapFromSource (), mapSelectionToSource (), and 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 dynamicSortFilter 特性。

基本 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.

排序

QTableView and QTreeView have a 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.

A sorted QTreeView

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 implement sort () in your model, or use a QSortFilterProxyModel to wrap your model -- QSortFilterProxyModel provides a generic sort () reimplementation that operates on the sortRole () ( Qt.DisplayRole by default) of the items and that understands several data types, including int , QString ,和 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 sortCaseSensitivity 特性。

Custom sorting behavior is achieved by subclassing QSortFilterProxyModel and reimplementing lessThan (), 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 {
         QRegExp *emailPattern = new QRegExp("([\\w\\.]*@[\\w\\.]*)");
         QString leftString = leftData.toString();
         if(left.column() == 1 && emailPattern->indexIn(leftString) != -1)
             leftString = emailPattern->cap(1);
         QString rightString = rightData.toString();
         if(right.column() == 1 && emailPattern->indexIn(rightString) != -1)
             rightString = emailPattern->cap(1);
         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 the QSortFilterProxyModel (or on the original model if it implements sort ()). 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.

过滤

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

Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow () and filterAcceptsColumn () functions. For example (from the Custom Sort/Filter Model example), the following implementation ignores the filterKeyColumn 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, using reset () 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.

子类化

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

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


方法文档编制

QSortFilterProxyModel.__init__ ( self , QObject   parent  = None)

parent argument, if not None, causes self to be owned by Qt instead of PyQt.

Constructs a sorting filter model with the given parent .

QModelIndex QSortFilterProxyModel.buddy ( self , QModelIndex   index )

重实现自 QAbstractItemModel.buddy ().

bool QSortFilterProxyModel.canFetchMore ( self , QModelIndex   parent )

重实现自 QAbstractItemModel.canFetchMore ().

QSortFilterProxyModel.clear ( self )

This method is also a Qt slot with the C++ signature void clear() .

int QSortFilterProxyModel.columnCount ( self , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.columnCount ().

QVariant QSortFilterProxyModel.data ( self , QModelIndex   index , int  role  = Qt.DisplayRole)

重实现自 QAbstractItemModel.data ().

另请参阅 setData ().

bool QSortFilterProxyModel.dropMimeData ( self , QMimeData   data , Qt.DropAction   action , int  row , int  column , QModelIndex   parent )

重实现自 QAbstractItemModel.dropMimeData ().

bool QSortFilterProxyModel.dynamicSortFilter ( self )

QSortFilterProxyModel.fetchMore ( self , QModelIndex   parent )

重实现自 QAbstractItemModel.fetchMore ().

bool QSortFilterProxyModel.filterAcceptsColumn ( self , int  source_column , QModelIndex   source_parent )

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 filterRole 特性。

另请参阅 filterAcceptsRow (), setFilterFixedString (), setFilterRegExp (), and setFilterWildcard ().

bool QSortFilterProxyModel.filterAcceptsRow ( self , int  source_row , QModelIndex   source_parent )

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 filterRole 特性。

另请参阅 filterAcceptsColumn (), setFilterFixedString (), setFilterRegExp (), and setFilterWildcard ().

Qt.CaseSensitivity QSortFilterProxyModel.filterCaseSensitivity ( self )

QSortFilterProxyModel.filterChanged ( self )

int QSortFilterProxyModel.filterKeyColumn ( self )

QRegExp QSortFilterProxyModel.filterRegExp ( self )

int QSortFilterProxyModel.filterRole ( self )

Qt.ItemFlags QSortFilterProxyModel.flags ( self , QModelIndex   index )

重实现自 QAbstractItemModel.flags ().

bool QSortFilterProxyModel.hasChildren ( self , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.hasChildren ().

QVariant QSortFilterProxyModel.headerData ( self , int  section , Qt.Orientation   orientation , int  role  = Qt.EditRole)

重实现自 QAbstractItemModel.headerData ().

另请参阅 setHeaderData ().

QModelIndex QSortFilterProxyModel.index ( self , int  row , int  column , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.index ().

bool QSortFilterProxyModel.insertColumns ( self , int  column , int  count , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.insertColumns ().

bool QSortFilterProxyModel.insertRows ( self , int  row , int  count , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.insertRows ().

QSortFilterProxyModel.invalidate ( self )

This method is also a Qt slot with the C++ signature void invalidate() .

Invalidates the current sorting and filtering.

该函数在 Qt 4.3 引入。

另请参阅 invalidateFilter ().

QSortFilterProxyModel.invalidateFilter ( self )

Invalidates the current filtering.

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

该函数在 Qt 4.3 引入。

另请参阅 invalidate ().

bool QSortFilterProxyModel.isSortLocaleAware ( self )

bool QSortFilterProxyModel.lessThan ( self , QModelIndex   left , QModelIndex   right )

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 QVariant types:

Any other type will be converted to a QString 使用 QVariant.toString ().

Comparison of QString s is case sensitive by default; this can be changed using the sortCaseSensitivity 特性。

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

注意: The indices passed in correspond to the source model.

另请参阅 sortRole , sortCaseSensitivity , and dynamicSortFilter .

QModelIndex QSortFilterProxyModel.mapFromSource ( self , QModelIndex   sourceIndex )

重实现自 QAbstractProxyModel.mapFromSource ().

Returns the model index in the QSortFilterProxyModel given the sourceIndex from the source model.

另请参阅 mapToSource ().

QItemSelection QSortFilterProxyModel.mapSelectionFromSource ( self , QItemSelection   sourceSelection )

重实现自 QAbstractProxyModel.mapSelectionFromSource ().

QItemSelection QSortFilterProxyModel.mapSelectionToSource ( self , QItemSelection   proxySelection )

重实现自 QAbstractProxyModel.mapSelectionToSource ().

QModelIndex QSortFilterProxyModel.mapToSource ( self , QModelIndex   proxyIndex )

重实现自 QAbstractProxyModel.mapToSource ().

Returns the source model index corresponding to the given proxyIndex from the sorting filter model.

另请参阅 mapFromSource ().

list-of-QModelIndex QSortFilterProxyModel.match ( self , QModelIndex   start , int  role , QVariant  value , int  hits  = 1, Qt.MatchFlags   flags  = Qt.MatchStartsWith|Qt.MatchWrap)

重实现自 QAbstractItemModel.match ().

QMimeData QSortFilterProxyModel.mimeData ( self , list-of-QModelIndex  indexes )

QMimeData result

重实现自 QAbstractItemModel.mimeData ().

QStringList QSortFilterProxyModel.mimeTypes ( self )

重实现自 QAbstractItemModel.mimeTypes ().

QModelIndex QSortFilterProxyModel.parent ( self , QModelIndex   child )

重实现自 QAbstractItemModel.parent ().

QObject QSortFilterProxyModel.parent ( self )

bool QSortFilterProxyModel.removeColumns ( self , int  column , int  count , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.removeColumns ().

bool QSortFilterProxyModel.removeRows ( self , int  row , int  count , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.removeRows ().

int QSortFilterProxyModel.rowCount ( self , QModelIndex   parent  = QModelIndex())

重实现自 QAbstractItemModel.rowCount ().

bool QSortFilterProxyModel.setData ( self , QModelIndex   index , QVariant  value , int  role  = Qt.EditRole)

重实现自 QAbstractItemModel.setData ().

另请参阅 data ().

QSortFilterProxyModel.setDynamicSortFilter ( self , bool  enable )

QSortFilterProxyModel.setFilterCaseSensitivity ( self , Qt.CaseSensitivity   cs )

QSortFilterProxyModel.setFilterFixedString ( self , QString  pattern )

This method is also a Qt slot with the C++ signature void setFilterFixedString(const QString&) .

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

另请参阅 setFilterCaseSensitivity (), setFilterRegExp (), setFilterWildcard (), and filterRegExp ().

QSortFilterProxyModel.setFilterKeyColumn ( self , int  column )

QSortFilterProxyModel.setFilterRegExp ( self , QRegExp   regExp )

QSortFilterProxyModel.setFilterRegExp ( self , QString  pattern )

This method is also a Qt slot with the C++ signature void setFilterRegExp(const QString&) .

QSortFilterProxyModel.setFilterRole ( self , int  role )

QSortFilterProxyModel.setFilterWildcard ( self , QString  pattern )

This method is also a Qt slot with the C++ signature void setFilterWildcard(const QString&) .

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

另请参阅 setFilterCaseSensitivity (), setFilterRegExp (), setFilterFixedString (), and filterRegExp ().

bool QSortFilterProxyModel.setHeaderData ( self , int  section , Qt.Orientation   orientation , QVariant  value , int  role  = Qt.EditRole)

重实现自 QAbstractItemModel.setHeaderData ().

另请参阅 headerData ().

QSortFilterProxyModel.setSortCaseSensitivity ( self , Qt.CaseSensitivity   cs )

QSortFilterProxyModel.setSortLocaleAware ( self , bool  on )

QSortFilterProxyModel.setSortRole ( self , int  role )

QSortFilterProxyModel.setSourceModel ( self , QAbstractItemModel   sourceModel )

重实现自 QAbstractProxyModel.setSourceModel ().

QSortFilterProxyModel.sort ( self , int  column , Qt.SortOrder   order  = Qt.AscendingOrder)

重实现自 QAbstractItemModel.sort ().

Qt.CaseSensitivity QSortFilterProxyModel.sortCaseSensitivity ( self )

int QSortFilterProxyModel.sortColumn ( self )

the column currently used for sorting

This returns the most recently used sort column.

该函数在 Qt 4.5 引入。

Qt.SortOrder QSortFilterProxyModel.sortOrder ( self )

the order currently used for sorting

This returns the most recently used sort order.

该函数在 Qt 4.5 引入。

int QSortFilterProxyModel.sortRole ( self )

QSize QSortFilterProxyModel.span ( self , QModelIndex   index )

重实现自 QAbstractItemModel.span ().

Qt.DropActions QSortFilterProxyModel.supportedDropActions ( self )

重实现自 QAbstractItemModel.supportedDropActions ().