Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmlrolesorter.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include <QtQmlModels/private/qqmlrolesorter_p.h>
5#include <QtQmlModels/private/qqmlsortfilterproxymodel_p.h>
6
7QT_BEGIN_NAMESPACE
8
9/*!
10 \qmltype RoleSorter
11 \inherits Sorter
12 \inqmlmodule QtQml.Models
13 \since 6.10
14 \preliminary
15 \brief Sort data in a \l SortFilterProxyModel based on configured role
16 name.
17
18 RoleSorter allows the user to sort the data according to the role name
19 as configured in the source model.
20
21 The RoleSorter can be configured in the sort filter proxy model as below,
22
23 \qml
24 SortFilterProxyModel {
25 model: sourceModel
26 sorters: [
27 RoleSorter { roleName: "firstname" }
28 ]
29 }
30 \endqml
31*/
32
33QQmlRoleSorter::QQmlRoleSorter(QObject *parent) :
34 QQmlSorterBase (new QQmlRoleSorterPrivate, parent)
35{
36}
37
38QQmlRoleSorter::QQmlRoleSorter(QQmlSorterBasePrivate *priv, QObject *parent) :
39 QQmlSorterBase (priv, parent)
40{
41}
42
43/*!
44 \qmlproperty string RoleSorter::roleName
45
46 This property holds the role name that will be used to sort the data.
47
48 The default value is display role.
49*/
50void QQmlRoleSorter::setRoleName(const QString& roleName)
51{
52 Q_D(QQmlRoleSorter);
53 if (d->m_roleName == roleName)
54 return;
55 d->m_roleName = roleName;
56 // Update the model for the change in the role name
57 emit roleNameChanged();
58 // Invalidate the model for the change in the role name
59 invalidate();
60}
61
62const QString& QQmlRoleSorter::roleName() const
63{
64 Q_D(const QQmlRoleSorter);
65 return d->m_roleName;
66}
67
68/*!
69 \internal
70*/
71QPartialOrdering QQmlRoleSorter::compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel *proxyModel) const
72{
73 Q_D(const QQmlRoleSorter);
74 if (int role = proxyModel->itemRoleForName(d->m_roleName); role > -1)
75 return QVariant::compare(proxyModel->sourceData(sourceLeft, role), proxyModel->sourceData(sourceRight, role));
76 return QPartialOrdering::Unordered;
77}
78
79QT_END_NAMESPACE
80
81#include "moc_qqmlrolesorter_p.cpp"