Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD

## com.trolltech.qt.gui
Class QSortFilterProxyModel

    java.lang.Object
      com.trolltech.qt.internal.QSignalEmitterInternal
          com.trolltech.qt.QSignalEmitter
              com.trolltech.qt.QtJambiObject
                  com.trolltech.qt.core.QObject
                      com.trolltech.qt.core.QAbstractItemModel
                          com.trolltech.qt.gui.QAbstractProxyModel
                              com.trolltech.qt.gui.QSortFilterProxyModel

All Implemented Interfaces:
  QtJambiInterface

    public class QSortFilterProxyModel

extends 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()` 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()`.

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:

            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.
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 `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:
The following code example is written in c++.

    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.SortOrder.AscendingOrder);

## 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 `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(new QRegExp(".png", Qt.CaseSensitivity.CaseInsensitive,
                                                QRegExp.PatternSyntax.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, the following implementation ignores the `filterKeyColumn` property and performs filtering on columns 0, 1, and 2:
The following code example is written in c++.

    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, note that `reset()` returns the proxy model to its original state, losing selection information, and will cause the proxy model to be repopulated.

## Subclassing

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

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.

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

Nested Class Summary

Nested classes/interfaces inherited from class com.trolltech.qt.QSignalEmitter
`QSignalEmitter.AbstractSignal, QSignalEmitter.Signal0, QSignalEmitter.Signal1, QSignalEmitter.Signal2, QSignalEmitter.Signal3, QSignalEmitter.Signal4, QSignalEmitter.Signal5, QSignalEmitter.Signal6, QSignalEmitter.Signal7, QSignalEmitter.Signal8, QSignalEmitter.Signal9`

Nested classes/interfaces inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
`com.trolltech.qt.internal.QSignalEmitterInternal.AbstractSignalInternal`

Field Summary

Fields inherited from class com.trolltech.qt.core.QAbstractItemModel
`dataChanged, headerDataChanged, layoutAboutToBeChanged, layoutChanged`

Fields inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
`currentSender`

Constructor Summary
`QSortFilterProxyModel()` Constructs a sorting filter model with the given `parent`.
`QSortFilterProxyModel(QObject parent)` Constructs a sorting filter model with the given `parent`.

Method Summary
`boolean` | `dynamicSortFilter()` This property holds whether the proxy model is dynamically sorted and filtered whenever the contents of the source model change.
`protected boolean` | `filterAcceptsColumn(int source_column, com.trolltech.qt.core.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.
`protected boolean` | `filterAcceptsRow(int source_row, com.trolltech.qt.core.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.
`Qt.CaseSensitivity` | `filterCaseSensitivity()` This property holds the case sensitivity of the `QRegExp` pattern used to filter the contents of the source model.
`int` | `filterKeyColumn()` This property holds the column where the key used to filter the contents of the source model is read from.
`QRegExp` | `filterRegExp()` This property holds the `QRegExp` used to filter the contents of the source model.
`int` | `filterRole()` This property holds the item role that is used to query the source model's data when filtering items.
`void` | `invalidate()` Invalidates the current sorting and filtering.
`protected void` | `invalidateFilter()` Invalidates the current filtering.
`boolean` | `isSortLocaleAware()` This property holds the local aware setting used for comparing strings when sorting.
`protected boolean` | `lessThan(com.trolltech.qt.core.QModelIndex left, com.trolltech.qt.core.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.
`void` | `setDynamicSortFilter(boolean enable)` This property holds whether the proxy model is dynamically sorted and filtered whenever the contents of the source model change.
`void` | `setFilterCaseSensitivity(Qt.CaseSensitivity cs)` This property holds the case sensitivity of the `QRegExp` pattern used to filter the contents of the source model.
`void` | `setFilterFixedString(java.lang.String pattern)` Sets the fixed string used to filter the contents of the source model to the given `pattern`.
`void` | `setFilterKeyColumn(int column)` This property holds the column where the key used to filter the contents of the source model is read from.
`void` | `setFilterRegExp(QRegExp regExp)` This property holds the `QRegExp` used to filter the contents of the source model.
`void` | `setFilterRegExp(java.lang.String pattern)` This property holds the `QRegExp` used to filter the contents of the source model.
`void` | `setFilterRole(int role)` This property holds the item role that is used to query the source model's data when filtering items.
`void` | `setFilterWildcard(java.lang.String pattern)` Sets the wildcard expression used to filter the contents of the source model to the given `pattern`.
`void` | `setSortCaseSensitivity(Qt.CaseSensitivity cs)` This property holds the case sensitivity setting used for comparing strings when sorting.
`void` | `setSortLocaleAware(boolean on)` This property holds the local aware setting used for comparing strings when sorting.
`void` | `setSortRole(int role)` This property holds the item role that is used to query the source model's data when sorting items.
`Qt.CaseSensitivity` | `sortCaseSensitivity()` This property holds the case sensitivity setting used for comparing strings when sorting.
`int` | `sortRole()` This property holds the item role that is used to query the source model's data when sorting items.

Methods inherited from class com.trolltech.qt.gui.QAbstractProxyModel
`mapFromSource, mapSelectionFromSource, mapSelectionToSource, mapToSource, setSourceModel, sourceModel`

Methods inherited from class com.trolltech.qt.core.QAbstractItemModel
`beginInsertColumns, beginInsertRows, beginRemoveColumns, beginRemoveRows, buddy, canFetchMore, changePersistentIndex, changePersistentIndexList, columnCount, columnCount, createIndex, createIndex, createIndex, data, data, data, data, dropMimeData, endInsertColumns, endInsertRows, endRemoveColumns, endRemoveRows, fetchMore, flags, hasChildren, hasChildren, hasIndex, hasIndex, headerData, headerData, index, index, insertColumn, insertColumn, insertColumns, insertColumns, insertRow, insertRow, insertRows, insertRows, itemData, match, match, match, match, mimeData, mimeTypes, parent, persistentIndexList, removeColumn, removeColumn, removeColumns, removeColumns, removeRow, removeRow, removeRows, removeRows, reset, revert, rowCount, rowCount, setData, setData, setData, setData, setHeaderData, setHeaderData, setItemData, setSupportedDragActions, setSupportedDragActions, sibling, sort, sort, span, submit, supportedDragActions, supportedDropActions`

Methods inherited from class com.trolltech.qt.core.QObject
`childEvent, children, connectSlotsByName, customEvent, disposeLater, dumpObjectInfo, dumpObjectTree, dynamicPropertyNames, event, eventFilter, findChild, findChild, findChild, findChildren, findChildren, findChildren, findChildren, indexOfProperty, installEventFilter, isWidgetType, killTimer, moveToThread, objectName, parent, properties, property, removeEventFilter, setObjectName, setParent, setProperty, startTimer, timerEvent, toString, userProperty`

Methods inherited from class com.trolltech.qt.QtJambiObject
`dispose, disposed, equals, finalize, reassignNativeResources, tr, tr, tr`

Methods inherited from class com.trolltech.qt.QSignalEmitter
`blockSignals, disconnect, disconnect, signalsBlocked, signalSender, thread`

Methods inherited from class com.trolltech.qt.internal.QSignalEmitterInternal
`__qt_signalInitialization`

Methods inherited from class java.lang.Object
`clone, getClass, hashCode, notify, notifyAll, wait, wait, wait`

Methods inherited from interface com.trolltech.qt.QtJambiInterface
`disableGarbageCollection, nativeId, nativePointer, reenableGarbageCollection, setJavaOwnership`

Constructor Detail

### QSortFilterProxyModel

    public QSortFilterProxyModel()

  Constructs a sorting filter model with the given `parent`.

### QSortFilterProxyModel

    public QSortFilterProxyModel(QObject parent)

  Constructs a sorting filter model with the given `parent`.

Method Detail

### dynamicSortFilter

    public final boolean dynamicSortFilter()

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

### filterCaseSensitivity

    public final Qt.CaseSensitivity filterCaseSensitivity()

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

### filterKeyColumn

    public final int filterKeyColumn()

  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.

### filterRegExp

    public final QRegExp filterRegExp()

  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.

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

### filterRole

    public final int filterRole()

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

### invalidate

    public final void invalidate()

  Invalidates the current sorting and filtering.

See also:
  `invalidateFilter()`.

### invalidateFilter

    protected final void invalidateFilter()

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

### isSortLocaleAware

    public final boolean isSortLocaleAware()

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

### setDynamicSortFilter

    public final void setDynamicSortFilter(boolean enable)

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

### setFilterCaseSensitivity

    public final void setFilterCaseSensitivity(Qt.CaseSensitivity cs)

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

### setFilterFixedString

    public final void setFilterFixedString(java.lang.String pattern)

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

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

### setFilterKeyColumn

    public final void setFilterKeyColumn(int column)

  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.

### setFilterRegExp

    public final void setFilterRegExp(QRegExp regExp)

  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.

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

### setFilterRegExp

    public final void setFilterRegExp(java.lang.String pattern)

  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.

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

### setFilterRole

    public final void setFilterRole(int role)

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

### setFilterWildcard

    public final void setFilterWildcard(java.lang.String pattern)

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

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

### setSortCaseSensitivity

    public final void setSortCaseSensitivity(Qt.CaseSensitivity cs)

  This property holds the case sensitivity setting used for comparing strings when sorting. By default, sorting is case sensitive.

See also:
  `filterCaseSensitivity`, and `lessThan()`.

### setSortLocaleAware

    public final void setSortLocaleAware(boolean on)

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

### setSortRole

    public final void setSortRole(int role)

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

### sortCaseSensitivity

    public final Qt.CaseSensitivity sortCaseSensitivity()

  This property holds the case sensitivity setting used for comparing strings when sorting. By default, sorting is case sensitive.

See also:
  `filterCaseSensitivity`, and `lessThan()`.

### sortRole

    public final int sortRole()

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

### filterAcceptsColumn

    protected boolean filterAcceptsColumn(int source_column,
                                          com.trolltech.qt.core.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.

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

### filterAcceptsRow

    protected boolean filterAcceptsRow(int source_row,
                                       com.trolltech.qt.core.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.

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

### lessThan

    protected boolean lessThan(com.trolltech.qt.core.QModelIndex left,
                               com.trolltech.qt.core.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:

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

Overview | Package | Class | Tree | Deprecated | Index | Help
PREV CLASS NEXT CLASS | FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD