QSortFilterProxyModel Class▲
-
Header: QSortFilterProxyModel
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Inherits: QAbstractProxyModel
-
Group: QSortFilterProxyModel is part of model-view
Detailed Description▲
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-&
gt;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-&
gt;setSourceModel(sourceModel);
treeView-&
gt;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