Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QSortFilterProxyModel Class

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

Header:#include <QSortFilterProxyModel>
Since: Qt 4.1
Inherits:QAbstractProxyModel

Properties

Public Functions

QSortFilterProxyModel(QObject * parent = 0)
~QSortFilterProxyModel()
booldynamicSortFilter() const
Qt::CaseSensitivityfilterCaseSensitivity() const
intfilterKeyColumn() const
QRegExpfilterRegExp() const
intfilterRole() const
boolisSortLocaleAware() const
voidsetDynamicSortFilter(bool enable)
voidsetFilterCaseSensitivity(Qt::CaseSensitivity cs)
voidsetFilterKeyColumn(int column)
voidsetFilterRegExp(const QRegExp & regExp)
voidsetFilterRole(int role)
voidsetSortCaseSensitivity(Qt::CaseSensitivity cs)
voidsetSortLocaleAware(bool on)
voidsetSortRole(int role)
Qt::CaseSensitivitysortCaseSensitivity() const
intsortColumn() const
Qt::SortOrdersortOrder() const
intsortRole() const

Reimplemented Public Functions

virtual QModelIndexbuddy(const QModelIndex & index) const
virtual boolcanFetchMore(const QModelIndex & parent) const
virtual intcolumnCount(const QModelIndex & parent = QModelIndex()) const
virtual QVariantdata(const QModelIndex & index, int role = Qt::DisplayRole) const
virtual booldropMimeData(const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent)
virtual voidfetchMore(const QModelIndex & parent)
virtual Qt::ItemFlagsflags(const QModelIndex & index) const
virtual boolhasChildren(const QModelIndex & parent = QModelIndex()) const
virtual QVariantheaderData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
virtual QModelIndexindex(int row, int column, const QModelIndex & parent = QModelIndex()) const
virtual boolinsertColumns(int column, int count, const QModelIndex & parent = QModelIndex())
virtual boolinsertRows(int row, int count, const QModelIndex & parent = QModelIndex())
virtual QModelIndexmapFromSource(const QModelIndex & sourceIndex) const
virtual QItemSelectionmapSelectionFromSource(const QItemSelection & sourceSelection) const
virtual QItemSelectionmapSelectionToSource(const QItemSelection & proxySelection) const
virtual QModelIndexmapToSource(const QModelIndex & proxyIndex) const
virtual QModelIndexListmatch(const QModelIndex & start, int role, const QVariant & value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags( Qt::MatchStartsWith | Qt::MatchWrap )) const
virtual QMimeData *mimeData(const QModelIndexList & indexes) const
virtual QStringListmimeTypes() const
virtual QModelIndexparent(const QModelIndex & child) const
virtual boolremoveColumns(int column, int count, const QModelIndex & parent = QModelIndex())
virtual boolremoveRows(int row, int count, const QModelIndex & parent = QModelIndex())
virtual introwCount(const QModelIndex & parent = QModelIndex()) const
virtual boolsetData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole)
virtual boolsetHeaderData(int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole)
virtual voidsetSourceModel(QAbstractItemModel * sourceModel)
virtual voidsort(int column, Qt::SortOrder order = Qt::AscendingOrder)
virtual QSizespan(const QModelIndex & index) const
virtual Qt::DropActionssupportedDropActions() const

Public Slots

voidinvalidate()
voidsetFilterFixedString(const QString & pattern)
voidsetFilterRegExp(const QString & pattern)
voidsetFilterWildcard(const QString & pattern)

Protected Functions

virtual boolfilterAcceptsColumn(int source_column, const QModelIndex & source_parent) const
virtual boolfilterAcceptsRow(int source_row, const QModelIndex & source_parent) const
voidinvalidateFilter()
virtual boollessThan(const QModelIndex & left, const QModelIndex & right) const

Additional Inherited Members

Detailed Description

TheQSortFilterProxyModel 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=newQTreeView;        MyItemModel*model=new MyItemModel(this);        treeView->setModel(model);

To add sorting and filtering support toMyItemModel, we need to create aQSortFilterProxyModel, callsetSourceModel() with theMyItemModel as argument, and install theQSortFilterProxyModel on the view:

QTreeView*treeView=newQTreeView;        MyItemModel*sourceModel=new MyItemModel(this);QSortFilterProxyModel*proxyModel=newQSortFilterProxyModel(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 theQSortFilterProxyModel are applied to the original model.

TheQSortFilterProxyModel acts as a wrapper for the original model. If you need to convert sourceQModelIndexes to sorted/filtered model indexes or vice versa, usemapToSource(),mapFromSource(),mapSelectionToSource(), andmapSelectionFromSource().

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

TheBasic Sort/Filter Model andCustom Sort/Filter Model examples illustrate how to useQSortFilterProxyModel to perform basic sorting and filtering and how to subclass it to implement custom behavior.

Sorting

QTableView andQTreeView have asortingEnabled 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 thesort() virtual function on the model to reorder the data in the model. To make your data sortable, you can either implementsort() in your model, or use aQSortFilterProxyModel to wrap your model --QSortFilterProxyModel provides a genericsort() reimplementation that operates on thesortRole() (Qt::DisplayRole by default) of the items and that understands several data types, includingint,QString, andQDateTime. For hierarchical models, sorting is applied recursively to all child items. String comparisons are case sensitive by default; this can be changed by setting thesortCaseSensitivity property.

Custom sorting behavior is achieved by subclassingQSortFilterProxyModel and reimplementinglessThan(), which is used to compare items. For example:

bool MySortFilterProxyModel::lessThan(constQModelIndex&left,constQModelIndex&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=newQRegExp("([\\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);returnQString::localeAwareCompare(leftString, rightString)<0;    }}

(This code snippet comes from theCustom 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 callingsort() with the desired column and order as arguments on theQSortFilterProxyModel (or on the original model if it implementssort()). 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.

Filtering

In addition to sorting,QSortFilterProxyModel can be used to hide items that do not match a certain filter. The filter is specified using aQRegExp object and is applied to thefilterRole() (Qt::DisplayRole by default) of each item, for a given column. TheQRegExp 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 aQLineEdit and to connect thetextChanged() signal tosetFilterRegExp(),setFilterWildcard(), orsetFilterFixedString() to reapply the filter.

Custom filtering behavior can be achieved by reimplementing thefilterAcceptsRow() andfilterAcceptsColumn() functions. For example (from theCustom Sort/Filter Model example), the following implementation ignores thefilterKeyColumn property and performs filtering on columns 0, 1, and 2:

bool MySortFilterProxyModel::filterAcceptsRow(int sourceRow,constQModelIndex&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 theCustom Sort/Filter Model example.)

If you are working with large amounts of filtering and have to invokeinvalidateFilter() repeatedly, usingreset() 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

SinceQAbstractProxyModel and its subclasses are derived fromQAbstractItemModel, 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 customhasChildren() implementation, you should also provide one in the proxy model.

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

See alsoQAbstractProxyModel,QAbstractItemModel,Model/View Programming,Basic Sort/Filter Model Example,Custom Sort/Filter Model Example, andQIdentityProxyModel.

Property Documentation

dynamicSortFilter :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 aQComboBox, then using functions that update the model, e.g.,addItem(), will not work as expected. An alternative is to set dynamicSortFilter to false and callsort() after adding items to theQComboBox.

The default value is false.

This property was introduced in Qt 4.2.

Access functions:

booldynamicSortFilter() const
voidsetDynamicSortFilter(bool enable)

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

Access functions:

Qt::CaseSensitivityfilterCaseSensitivity() const
voidsetFilterCaseSensitivity(Qt::CaseSensitivity cs)

See alsofilterRegExp andsortCaseSensitivity.

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

intfilterKeyColumn() const
voidsetFilterKeyColumn(int column)

filterRegExp :QRegExp

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

Setting this property overwrites the currentfilterCaseSensitivity. By default, theQRegExp is an empty string matching all contents.

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

Access functions:

QRegExpfilterRegExp() const
voidsetFilterRegExp(const QRegExp & regExp)
voidsetFilterRegExp(const QString & pattern)

See alsofilterCaseSensitivity,setFilterWildcard(), andsetFilterFixedString().

filterRole :int

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

The default value isQt::DisplayRole.

This property was introduced in Qt 4.2.

Access functions:

intfilterRole() const
voidsetFilterRole(int role)

See alsofilterAcceptsRow().

isSortLocaleAware :bool

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

By default, sorting is not local aware.

This property was introduced in Qt 4.3.

Access functions:

boolisSortLocaleAware() const
voidsetSortLocaleAware(bool on)

See alsosortCaseSensitivity andlessThan().

sortCaseSensitivity :Qt::CaseSensitivity

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

By default, sorting is case sensitive.

This property was introduced in Qt 4.2.

Access functions:

Qt::CaseSensitivitysortCaseSensitivity() const
voidsetSortCaseSensitivity(Qt::CaseSensitivity cs)

See alsofilterCaseSensitivity andlessThan().

sortRole :int

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

The default value isQt::DisplayRole.

This property was introduced in Qt 4.2.

Access functions:

intsortRole() const
voidsetSortRole(int role)

See alsolessThan().

Member Function Documentation

QSortFilterProxyModel::QSortFilterProxyModel(QObject * parent = 0)

Constructs a sorting filter model with the givenparent.

QSortFilterProxyModel::~QSortFilterProxyModel()

Destroys this sorting filter model.

[virtual]QModelIndex QSortFilterProxyModel::buddy(constQModelIndex & index) const

Reimplemented fromQAbstractItemModel::buddy().

[virtual]bool QSortFilterProxyModel::canFetchMore(constQModelIndex & parent) const

Reimplemented fromQAbstractItemModel::canFetchMore().

[virtual]int QSortFilterProxyModel::columnCount(constQModelIndex & parent = QModelIndex()) const

Reimplemented fromQAbstractItemModel::columnCount().

[virtual]QVariant QSortFilterProxyModel::data(constQModelIndex & index,int role = Qt::DisplayRole) const

Reimplemented fromQAbstractItemModel::data().

See alsosetData().

[virtual]bool QSortFilterProxyModel::dropMimeData(constQMimeData * data,Qt::DropAction action,int row,int column, constQModelIndex & parent)

Reimplemented fromQAbstractItemModel::dropMimeData().

[virtual]void QSortFilterProxyModel::fetchMore(constQModelIndex & parent)

Reimplemented fromQAbstractItemModel::fetchMore().

[virtual protected]bool QSortFilterProxyModel::filterAcceptsColumn(int source_column, constQModelIndex & source_parent) const

Returns true if the item in the column indicated by the givensource_column andsource_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, theQt::DisplayRole is used to determine if the row should be accepted or not. This can be changed by setting thefilterRole property.

See alsofilterAcceptsRow(),setFilterFixedString(),setFilterRegExp(), andsetFilterWildcard().

[virtual protected]bool QSortFilterProxyModel::filterAcceptsRow(int source_row, constQModelIndex & source_parent) const

Returns true if the item in the row indicated by the givensource_row andsource_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, theQt::DisplayRole is used to determine if the row should be accepted or not. This can be changed by setting thefilterRole property.

See alsofilterAcceptsColumn(),setFilterFixedString(),setFilterRegExp(), andsetFilterWildcard().

[virtual]Qt::ItemFlags QSortFilterProxyModel::flags(constQModelIndex & index) const

Reimplemented fromQAbstractItemModel::flags().

[virtual]bool QSortFilterProxyModel::hasChildren(constQModelIndex & parent = QModelIndex()) const

Reimplemented fromQAbstractItemModel::hasChildren().

[virtual]QVariant QSortFilterProxyModel::headerData(int section,Qt::Orientation orientation,int role = Qt::DisplayRole) const

Reimplemented fromQAbstractItemModel::headerData().

See alsosetHeaderData().

[virtual]QModelIndex QSortFilterProxyModel::index(int row,int column, constQModelIndex & parent = QModelIndex()) const

Reimplemented fromQAbstractItemModel::index().

[virtual]bool QSortFilterProxyModel::insertColumns(int column,int count, constQModelIndex & parent = QModelIndex())

Reimplemented fromQAbstractItemModel::insertColumns().

[virtual]bool QSortFilterProxyModel::insertRows(int row,int count, constQModelIndex & parent = QModelIndex())

Reimplemented fromQAbstractItemModel::insertRows().

[slot]void QSortFilterProxyModel::invalidate()

Invalidates the current sorting and filtering.

This function was introduced in Qt 4.3.

See alsoinvalidateFilter().

[protected]void QSortFilterProxyModel::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.

This function was introduced in Qt 4.3.

See alsoinvalidate().

[virtual protected]bool QSortFilterProxyModel::lessThan(constQModelIndex & left, constQModelIndex & right) const

Returns true if the value of the item referred to by the given indexleft is less than the value of the item referred to by the given indexright, otherwise returns false.

This function is used as the < operator when sorting, and handles the followingQVariant types:

Any other type will be converted to aQString usingQVariant::toString().

Comparison ofQStrings is case sensitive by default; this can be changed using thesortCaseSensitivity property.

By default, theQt::DisplayRole associated with theQModelIndexes is used for comparisons. This can be changed by setting thesortRole property.

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

See alsosortRole,sortCaseSensitivity, anddynamicSortFilter.

[virtual]QModelIndex QSortFilterProxyModel::mapFromSource(constQModelIndex & sourceIndex) const

Reimplemented fromQAbstractProxyModel::mapFromSource().

Returns the model index in theQSortFilterProxyModel given thesourceIndex from the source model.

See alsomapToSource().

[virtual]QItemSelection QSortFilterProxyModel::mapSelectionFromSource(constQItemSelection & sourceSelection) const

Reimplemented fromQAbstractProxyModel::mapSelectionFromSource().

[virtual]QItemSelection QSortFilterProxyModel::mapSelectionToSource(constQItemSelection & proxySelection) const

Reimplemented fromQAbstractProxyModel::mapSelectionToSource().

[virtual]QModelIndex QSortFilterProxyModel::mapToSource(constQModelIndex & proxyIndex) const

Reimplemented fromQAbstractProxyModel::mapToSource().

Returns the source model index corresponding to the givenproxyIndex from the sorting filter model.

See alsomapFromSource().

[virtual]QModelIndexList QSortFilterProxyModel::match(constQModelIndex & start,int role, constQVariant & value,int hits = 1,Qt::MatchFlags flags = Qt::MatchFlags( Qt::MatchStartsWith | Qt::MatchWrap )) const

Reimplemented fromQAbstractItemModel::match().

[virtual]QMimeData * QSortFilterProxyModel::mimeData(constQModelIndexList & indexes) const

Reimplemented fromQAbstractItemModel::mimeData().

[virtual]QStringList QSortFilterProxyModel::mimeTypes() const

Reimplemented fromQAbstractItemModel::mimeTypes().

[virtual]QModelIndex QSortFilterProxyModel::parent(constQModelIndex & child) const

Reimplemented fromQAbstractItemModel::parent().

[virtual]bool QSortFilterProxyModel::removeColumns(int column,int count, constQModelIndex & parent = QModelIndex())

Reimplemented fromQAbstractItemModel::removeColumns().

[virtual]bool QSortFilterProxyModel::removeRows(int row,int count, constQModelIndex & parent = QModelIndex())

Reimplemented fromQAbstractItemModel::removeRows().

[virtual]int QSortFilterProxyModel::rowCount(constQModelIndex & parent = QModelIndex()) const

Reimplemented fromQAbstractItemModel::rowCount().

[virtual]bool QSortFilterProxyModel::setData(constQModelIndex & index, constQVariant & value,int role = Qt::EditRole)

Reimplemented fromQAbstractItemModel::setData().

See alsodata().

[slot]void QSortFilterProxyModel::setFilterFixedString(constQString & pattern)

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

See alsosetFilterCaseSensitivity(),setFilterRegExp(),setFilterWildcard(), andfilterRegExp().

[slot]void QSortFilterProxyModel::setFilterWildcard(constQString & pattern)

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

See alsosetFilterCaseSensitivity(),setFilterRegExp(),setFilterFixedString(), andfilterRegExp().

[virtual]bool QSortFilterProxyModel::setHeaderData(int section,Qt::Orientation orientation, constQVariant & value,int role = Qt::EditRole)

Reimplemented fromQAbstractItemModel::setHeaderData().

See alsoheaderData().

[virtual]void QSortFilterProxyModel::setSourceModel(QAbstractItemModel * sourceModel)

Reimplemented fromQAbstractProxyModel::setSourceModel().

[virtual]void QSortFilterProxyModel::sort(int column,Qt::SortOrder order = Qt::AscendingOrder)

Reimplemented fromQAbstractItemModel::sort().

int QSortFilterProxyModel::sortColumn() const

the column currently used for sorting

This returns the most recently used sort column.

This function was introduced in Qt 4.5.

Qt::SortOrder QSortFilterProxyModel::sortOrder() const

the order currently used for sorting

This returns the most recently used sort order.

This function was introduced in Qt 4.5.

[virtual]QSize QSortFilterProxyModel::span(constQModelIndex & index) const

Reimplemented fromQAbstractItemModel::span().

[virtual]Qt::DropActions QSortFilterProxyModel::supportedDropActions() const

Reimplemented fromQAbstractItemModel::supportedDropActions().

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp