QSortFilterProxyModel Class Reference

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

  1. #include <QSortFilterProxyModel>

Inherits: QAbstractProxyModel.

This class was introduced in Qt 4.1.

Detailed Description

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:

  1.         QTreeView *treeView = new QTreeView;
  2.         MyItemModel *model = new MyItemModel(this);
  3.  
  4.         treeView->setModel(model);

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

  1.         QTreeView *treeView = new QTreeView;
  2.         MyItemModel *sourceModel = new MyItemModel(this);
  3.         QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
  4.  
  5.         proxyModel->setSourceModel(sourceModel);
  6.         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 QModelIndexes to sorted/filtered model indexes or vice versa, use mapToSource(), mapFromSource(), mapSelectionToSource(), and 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 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 and QTreeView have a sortingEnabled property that controls whether the user can sort the view by clicking the view's horizontal header. For example:

  1.         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

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, and 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 property.

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

  1. bool MySortFilterProxyModel::lessThan(const QModelIndex &left,
  2.                                       const QModelIndex &right) const
  3.  {
  4.     QVariant leftData = sourceModel()->data(left);
  5.     QVariant rightData = sourceModel()->data(right);
  6.  
  7.     if (leftData.type() == QVariant::DateTime)  {
  8.         return leftData.toDateTime() < rightData.toDateTime();
  9.     } else  {
  10.         QRegExp *emailPattern = new QRegExp("([\\w\\.]*@[\\w\\.]*)");
  11.  
  12.         QString leftString = leftData.toString();
  13.         if(left.column() == 1 && emailPattern->indexIn(leftString) != -1)
  14.             leftString = emailPattern->cap(1);
  15.  
  16.         QString rightString = rightData.toString();
  17.         if(right.column() == 1 && emailPattern->indexIn(rightString) != -1)
  18.             rightString = emailPattern->cap(1);
  19.  
  20.         return QString::localeAwareCompare(leftString, rightString) < 0;
  21.     }
  22. }

(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:

  1.         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 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:

  1.         proxyModel->setFilterRegExp(QRegExp(".png", Qt::CaseInsensitive,
  2.                                             QRegExp::FixedString));
  3.         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:

  1. bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow,
  2.         const QModelIndex &sourceParent) const
  3.  {
  4.     QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
  5.     QModelIndex index1 = sourceModel()->index(sourceRow, 1, sourceParent);
  6.     QModelIndex index2 = sourceModel()->index(sourceRow, 2, sourceParent);
  7.  
  8.     return (sourceModel()->data(index0).toString().contains(filterRegExp())
  9.             || sourceModel()->data(index1).toString().contains(filterRegExp()))
  10.            && dateInRange(sourceModel()->data(index2).toDate());
  11. }

(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.

Subclassing

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.

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

See also QAbstractProxyModel, QAbstractItemModel, Model/View Programming, Basic Sort/Filter Model Example, and Custom Sort/Filter Model Example.

Properties

Toggle detailsdynamicSortFilterdynamicSortFilter : 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 dynamicSortFilter is true. For instance, if you set the proxy model on a QComboBox, then using functions that update the model, e.g., addItem(), will not work as expected. An alternative is to set dynamicSortFilter to false and call sort() after adding items to the QComboBox.

The default value is false.

Access functions:

Look up this member in the source code.

Toggle detailsfilterCaseSensitivityfilterCaseSensitivity : Qt::CaseSensitivity

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

By default, the filter is case sensitive.

See also filterRegExp and sortCaseSensitivity.

Access functions:

Look up this member in the source code.

Toggle detailsfilterKeyColumnfilterKeyColumn : 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.

Access functions:

Look up this member in the source code.

Toggle detailsfilterRegExpfilterRegExp : QRegExp

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

Setting this property overwrites the current filterCaseSensitivity. By default, the QRegExp is an empty string matching all contents.

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

See also filterCaseSensitivity, setFilterWildcard(), and setFilterFixedString().

Access functions:

Look up this member in the source code.

Toggle detailsfilterRolefilterRole : 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.

See also filterAcceptsRow().

Access functions:

Look up this member in the source code.

Toggle detailsisSortLocaleAwareisSortLocaleAware : bool

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

By default, sorting is not local aware.

See also sortCaseSensitivity and lessThan().

Access functions:

Look up this member in the source code.

Toggle detailssortCaseSensitivitysortCaseSensitivity : Qt::CaseSensitivity

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

By default, sorting is case sensitive.

See also filterCaseSensitivity and lessThan().

Access functions:

Look up this member in the source code.

Toggle detailssortRolesortRole : 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.

See also lessThan().

Access functions:

Look up this member in the source code.

    Public Functions

    Toggle details QSortFilterProxyModel

    QSortFilterProxyModelQSortFilterProxyModel ( QObject *parent=0 ) ( QObject *parent=0 )

    Constructs a sorting filter model with the given parent.

    Look up this member in the source code.

    Toggle details QSortFilterProxyModel

    ~QSortFilterProxyModel~QSortFilterProxyModel () ()

    Destroys this sorting filter model.

    Look up this member in the source code.

    Toggle details QModelIndex QSortFilterProxyModel

    buddybuddy ( const QModelIndex &index ) ( const QModelIndex &index )const [virtual]

    Reimplemented from QAbstractItemModel::buddy().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    canFetchMorecanFetchMore ( const QModelIndex &parent ) ( const QModelIndex &parent )const [virtual]

    Reimplemented from QAbstractItemModel::canFetchMore().

    Look up this member in the source code.

    Toggle details int QSortFilterProxyModel

    columnCountcolumnCount ( const QModelIndex &parent=QModelIndex() ...) ( const QModelIndex &parent=QModelIndex() )const [virtual]

    Reimplemented from QAbstractItemModel::columnCount().

    Look up this member in the source code.

    Toggle details QVariant QSortFilterProxyModel

    datadata ( const QModelIndex &index , int role=Qt::DisplayRole ...) ( const QModelIndex &index , int role=Qt::DisplayRole )const [virtual]

    Reimplemented from QAbstractItemModel::data().

    See also setData().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    dropMimeDatadropMimeData ( const QMimeData *data , Qt::DropAction action , int row , int column , const QModelIndex &parent ...) ( const QMimeData *data , Qt::DropAction action , int row , int column , const QModelIndex &parent ) [virtual]

    Reimplemented from QAbstractItemModel::dropMimeData().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    fetchMorefetchMore ( const QModelIndex &parent ) ( const QModelIndex &parent ) [virtual]

    Reimplemented from QAbstractItemModel::fetchMore().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    filterAcceptsColumnfilterAcceptsColumn ( int source_column , const QModelIndex &source_parent ...) ( int source_column , const QModelIndex &source_parent )const [virtual protected]

    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 filterRole property.

    See also filterAcceptsRow(), setFilterFixedString(), setFilterRegExp(), and setFilterWildcard().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    filterAcceptsRowfilterAcceptsRow ( int source_row , const QModelIndex &source_parent ...) ( int source_row , const QModelIndex &source_parent )const [virtual protected]

    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 filterRole property.

    See also filterAcceptsColumn(), setFilterFixedString(), setFilterRegExp(), and setFilterWildcard().

    Look up this member in the source code.

    Toggle details Qt::ItemFlags QSortFilterProxyModel

    flagsflags ( const QModelIndex &index ) ( const QModelIndex &index )const [virtual]

    Reimplemented from QAbstractItemModel::flags().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    hasChildrenhasChildren ( const QModelIndex &parent=QModelIndex() ...) ( const QModelIndex &parent=QModelIndex() )const [virtual]

    Reimplemented from QAbstractItemModel::hasChildren().

    Look up this member in the source code.

    Toggle details QVariant QSortFilterProxyModel

    headerDataheaderData ( int section , Qt::Orientation orientation , int role=Qt::DisplayRole ...) ( int section , Qt::Orientation orientation , int role=Qt::DisplayRole )const [virtual]

    Reimplemented from QAbstractItemModel::headerData().

    See also setHeaderData().

    Look up this member in the source code.

    Toggle details QModelIndex QSortFilterProxyModel

    indexindex ( int row , int column , const QModelIndex &parent=QModelIndex() ...) ( int row , int column , const QModelIndex &parent=QModelIndex() )const [virtual]

    Reimplemented from QAbstractItemModel::index().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    insertColumnsinsertColumns ( int column , int count , const QModelIndex &parent=QModelIndex() ...) ( int column , int count , const QModelIndex &parent=QModelIndex() ) [virtual]

    Reimplemented from QAbstractItemModel::insertColumns().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    insertRowsinsertRows ( int row , int count , const QModelIndex &parent=QModelIndex() ...) ( int row , int count , const QModelIndex &parent=QModelIndex() ) [virtual]

    Reimplemented from QAbstractItemModel::insertRows().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    invalidateFilterinvalidateFilter () ()[protected]

    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 invalidate().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    lessThanlessThan ( const QModelIndex &left , const QModelIndex &right ...) ( const QModelIndex &left , const QModelIndex &right )const [virtual protected]

    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 using QVariant::toString().

    Comparison of QStrings is case sensitive by default; this can be changed using the sortCaseSensitivity property.

    By default, the Qt::DisplayRole associated with the QModelIndexes is used for comparisons. This can be changed by setting the sortRole property.

    Note: The indices passed in correspond to the source model.

    See also sortRole, sortCaseSensitivity, and dynamicSortFilter.

    Look up this member in the source code.

    Toggle details QModelIndex QSortFilterProxyModel

    mapFromSourcemapFromSource ( const QModelIndex &sourceIndex ...) ( const QModelIndex &sourceIndex )const [virtual]

    Reimplemented from QAbstractProxyModel::mapFromSource().

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

    See also mapToSource().

    Look up this member in the source code.

    Toggle details QItemSelection QSortFilterProxyModel

    mapSelectionFromSourcemapSelectionFromSource ( const QItemSelection &sourceSelection ...) ( const QItemSelection &sourceSelection )const [virtual]

    Look up this member in the source code.

    Toggle details QItemSelection QSortFilterProxyModel

    mapSelectionToSourcemapSelectionToSource ( const QItemSelection &proxySelection ...) ( const QItemSelection &proxySelection )const [virtual]

    Look up this member in the source code.

    Toggle details QModelIndex QSortFilterProxyModel

    mapToSourcemapToSource ( const QModelIndex &proxyIndex ...) ( const QModelIndex &proxyIndex )const [virtual]

    Reimplemented from QAbstractProxyModel::mapToSource().

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

    See also mapFromSource().

    Look up this member in the source code.

    Toggle details QModelIndexList QSortFilterProxyModel

    matchmatch ( const QModelIndex &start , int role , const QVariant &value , int hits=1 , Qt::MatchFlags flags=Qt::MatchFlags( Qt::MatchStartsWith | Qt::MatchWrap ) ...) ( const QModelIndex &start , int role , const QVariant &value , int hits=1 , Qt::MatchFlags flags=Qt::MatchFlags( Qt::MatchStartsWith | Qt::MatchWrap ) )const [virtual]

    Reimplemented from QAbstractItemModel::match().

    Look up this member in the source code.

    Toggle details QMimeData * QSortFilterProxyModel

    mimeDatamimeData ( const QModelIndexList &indexes ...) ( const QModelIndexList &indexes )const [virtual]

    Reimplemented from QAbstractItemModel::mimeData().

    Look up this member in the source code.

    Toggle details QStringList QSortFilterProxyModel

    mimeTypesmimeTypes () ()const [virtual]

    Reimplemented from QAbstractItemModel::mimeTypes().

    Look up this member in the source code.

    Toggle details QModelIndex QSortFilterProxyModel

    parentparent ( const QModelIndex &child ) ( const QModelIndex &child )const [virtual]

    Reimplemented from QAbstractItemModel::parent().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    removeColumnsremoveColumns ( int column , int count , const QModelIndex &parent=QModelIndex() ...) ( int column , int count , const QModelIndex &parent=QModelIndex() ) [virtual]

    Reimplemented from QAbstractItemModel::removeColumns().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    removeRowsremoveRows ( int row , int count , const QModelIndex &parent=QModelIndex() ...) ( int row , int count , const QModelIndex &parent=QModelIndex() ) [virtual]

    Reimplemented from QAbstractItemModel::removeRows().

    Look up this member in the source code.

    Toggle details int QSortFilterProxyModel

    rowCountrowCount ( const QModelIndex &parent=QModelIndex() ...) ( const QModelIndex &parent=QModelIndex() )const [virtual]

    Reimplemented from QAbstractItemModel::rowCount().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    setDatasetData ( const QModelIndex &index , const QVariant &value , int role=Qt::EditRole ...) ( const QModelIndex &index , const QVariant &value , int role=Qt::EditRole ) [virtual]

    Reimplemented from QAbstractItemModel::setData().

    See also data().

    Look up this member in the source code.

    Toggle details bool QSortFilterProxyModel

    setHeaderDatasetHeaderData ( int section , Qt::Orientation orientation , const QVariant &value , int role=Qt::EditRole ...) ( int section , Qt::Orientation orientation , const QVariant &value , int role=Qt::EditRole ) [virtual]

    Reimplemented from QAbstractItemModel::setHeaderData().

    See also headerData().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    setSourceModelsetSourceModel ( QAbstractItemModel *sourceModel ...) ( QAbstractItemModel *sourceModel ) [virtual]

    Reimplemented from QAbstractProxyModel::setSourceModel().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    sortsort ( int column , Qt::SortOrder order=Qt::AscendingOrder ...) ( int column , Qt::SortOrder order=Qt::AscendingOrder ) [virtual]

    Reimplemented from QAbstractItemModel::sort().

    Look up this member in the source code.

    Toggle details int QSortFilterProxyModel

    sortColumnsortColumn () ()const

    the column currently used for sorting

    This returns the most recently used sort column.

    Look up this member in the source code.

    Toggle details Qt::SortOrder QSortFilterProxyModel

    sortOrdersortOrder () ()const

    the order currently used for sorting

    This returns the most recently used sort order.

    Look up this member in the source code.

    Toggle details QSize QSortFilterProxyModel

    spanspan ( const QModelIndex &index ) ( const QModelIndex &index )const [virtual]

    Reimplemented from QAbstractItemModel::span().

    Look up this member in the source code.

    Toggle details Qt::DropActions QSortFilterProxyModel

    supportedDropActionssupportedDropActions () ()const [virtual]

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    filterChangedfilterChanged () ()[protected] Obsolete function

    This function is obsolete. Use invalidateFilter() instead.

    Look up this member in the source code.

    Public Slots

    Toggle details void QSortFilterProxyModel

    invalidateinvalidate () () [slot]

    Invalidates the current sorting and filtering.

    See also invalidateFilter().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    setFilterFixedStringsetFilterFixedString ( const QString &pattern ) ( const QString &pattern ) [slot]

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

    See also setFilterCaseSensitivity(), setFilterRegExp(), setFilterWildcard(), and filterRegExp().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    setFilterWildcardsetFilterWildcard ( const QString &pattern ) ( const QString &pattern ) [slot]

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

    See also setFilterCaseSensitivity(), setFilterRegExp(), setFilterFixedString(), and filterRegExp().

    Look up this member in the source code.

    Toggle details void QSortFilterProxyModel

    clearclear () () [slot] Obsolete function

    This function is obsolete. Use invalidate() instead.

    Look up this member in the source code.

    Notes provided by the Qt Community

    No notes