Home · All Classes · Modules

QSortFilterProxyModel Class Reference
[QtGui module]

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

Inherits QAbstractProxyModel.

Methods


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:

    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() with the 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 QModelIndexes to sorted/filtered model indexes or vice versa, use mapToSource(), mapFromSource(), mapSelectionToSource(), and mapSelectionFromSource().

By default, sorting and filtering isn't dynamically reapplied whenever the data of the original model changes, as an optimization. To enable dynamic sorting and filtering, call setDynamicSortFilter(true). At any time, you can call clear() to resort/refilter the data.

Sorting

QHeaderView has a showSortIndicator() property and a setClickable() function that together control whether the user can sort the view by clicking the view's horizontal header. For example:

    treeView->header()->setClickable(true);
    treeView->header()->setSortIndicatorShown(true);

When this feature is on, 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 you use a QSortFilterProxyModel to wrap your model -- QSortFilterProxyModel provides a generic sort() reimplementation that operates on the Qt.DisplayRole 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.

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 {
            return QString.localeAwareCompare(leftData.toString(),
                                               rightData.toString()) < 0;
        }
    }

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

The Sorting Model example illustrates how to use QSortFilterProxyModel to perform basic sorting.

Filtering

In addition to sorting, QSortFilterProxyModel can be used to hide items that don't match a certain filter. The filter is specified using a QRegExp object and is applied to the Qt.DisplayRole 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.

Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow() and filterAcceptsColumn() functions. For 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());
    }

See also QAbstractProxyModel, QAbstractItemModel, and Model/View Programming.


Method Documentation

QSortFilterProxyModel.__init__ (self, QObject parent = None)

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

bool QSortFilterProxyModel.canFetchMore (self, QModelIndex parent)

QSortFilterProxyModel.clear (self)

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

Clears this sorting filter model, removing all mapping.

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

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

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

QSortFilterProxyModel.fetchMore (self, QModelIndex parent)

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

Returns true if the value in the item in the column indicated by the given source_column and source_parent should be included in the model.

The default implementation returns true.

See also filterAcceptsRow().

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

Returns true if the value in the item in the row indicated by the given source_row and source_parent should be included in the model.

The default implementation uses filterRegExp with the data returned for the Qt.DisplayRole to determine if the row should be accepted or not.

See also filterAcceptsColumn().

Qt.CaseSensitivity QSortFilterProxyModel.filterCaseSensitivity (self)

int QSortFilterProxyModel.filterKeyColumn (self)

QRegExp QSortFilterProxyModel.filterRegExp (self)

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

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

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

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

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

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

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

See also sort().

QModelIndex QSortFilterProxyModel.mapFromSource (self, QModelIndex sourceIndex)

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

Reimplemented from QAbstractProxyModel.

See also mapToSource().

QItemSelection QSortFilterProxyModel.mapSelectionFromSource (self, QItemSelection sourceSelection)

QItemSelection QSortFilterProxyModel.mapSelectionToSource (self, QItemSelection proxySelection)

QModelIndex QSortFilterProxyModel.mapToSource (self, QModelIndex proxyIndex)

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

Reimplemented from QAbstractProxyModel.

See also mapFromSource().

QModelIndex-list QSortFilterProxyModel.match (self, QModelIndex start, int role, QVariant value, int hits, Qt.MatchFlags flags)

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

The QMimeData result

QModelIndex QSortFilterProxyModel.parent (self, QModelIndex child)

QObject QSortFilterProxyModel.parent (self)

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

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

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

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

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.

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

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

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

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

QSortFilterProxyModel.setSourceModel (self, QAbstractItemModel sourceModel)

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

QSize QSortFilterProxyModel.span (self, QModelIndex index)


PyQt 4.0.1 for X11Copyright © Riverbank Computing Ltd and Trolltech AS 2006Qt 4.1.4