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// Qt-Security score:significant reason:default
4
5#include <QtQmlModels/private/qqmlrolesorter_p.h>
6#include <QtQmlModels/private/qqmlsortfilterproxymodel_p.h>
7
8QT_BEGIN_NAMESPACE
9
10/*!
11 \qmltype RoleSorter
12 \inherits Sorter
13 \inqmlmodule QtQml.Models
14 \since 6.10
15 \preliminary
16 \brief Sort data in a \l SortFilterProxyModel based on configured role
17 name.
18
19 RoleSorter allows the user to sort the data according to the role name
20 as configured in the source model.
21
22 The RoleSorter can be configured in the sort filter proxy model as below,
23
24 \qml
25 SortFilterProxyModel {
26 model: sourceModel
27 sorters: [
28 RoleSorter { roleName: "firstname" }
29 ]
30 }
31 \endqml
32*/
33
34QQmlRoleSorter::QQmlRoleSorter(QObject *parent) :
35 QQmlSorterBase (new QQmlRoleSorterPrivate, parent)
36{
37}
38
39QQmlRoleSorter::QQmlRoleSorter(QQmlSorterBasePrivate *priv, QObject *parent) :
40 QQmlSorterBase (priv, parent)
41{
42}
43
44/*!
45 \qmlproperty string RoleSorter::roleName
46
47 This property holds the role name that will be used to sort the data.
48
49 The default value is display role.
50*/
51void QQmlRoleSorter::setRoleName(const QString& roleName)
52{
53 Q_D(QQmlRoleSorter);
54 if (d->m_roleName == roleName)
55 return;
56 d->m_roleName = roleName;
57 // Update the model for the change in the role name
58 emit roleNameChanged();
59 // Invalidate the model for the change in the role name
60 invalidate();
61}
62
63const QString& QQmlRoleSorter::roleName() const
64{
65 Q_D(const QQmlRoleSorter);
66 return d->m_roleName;
67}
68
69/*!
70 \internal
71*/
72QPartialOrdering QQmlRoleSorter::compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel *proxyModel) const
73{
74 Q_D(const QQmlRoleSorter);
75 if (int role = proxyModel->itemRoleForName(d->m_roleName); role > -1)
76 return QVariant::compare(proxyModel->sourceData(sourceLeft, role), proxyModel->sourceData(sourceRight, role));
77 return QPartialOrdering::Unordered;
78}
79
80QT_END_NAMESPACE
81
82#include "moc_qqmlrolesorter_p.cpp"