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 sourceModel: model
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 d->m_roleNameValidated = false;
58 // Update the model for the change in the role name
59 emit roleNameChanged();
60 // Invalidate the model for the change in the role name
61 invalidate();
62}
63
64const QString& QQmlRoleSorter::roleName() const
65{
66 Q_D(const QQmlRoleSorter);
67 return d->m_roleName;
68}
69
70/*!
71 \internal
72*/
73QPartialOrdering QQmlRoleSorter::compare(const QModelIndex& sourceLeft, const QModelIndex& sourceRight, const QQmlSortFilterProxyModel *proxyModel) const
74{
75 Q_D(const QQmlRoleSorter);
76 int role = proxyModel->itemRoleForName(d->m_roleName);
77
78 if (role < 0) {
79 if (!d->m_roleName.isEmpty() && !d->m_roleNameValidated) {
80 qWarning("Provided role name %s doesn't exist in the model", d->m_roleName.toUtf8().constData());
81 d->m_roleNameValidated = true;
82 }
83 return QPartialOrdering::Unordered;
84 }
85
86 return QVariant::compare(proxyModel->sourceData(sourceLeft, role), proxyModel->sourceData(sourceRight, role));
87}
88
89void QQmlRoleSorter::update(const QQmlSortFilterProxyModel *)
90{
91 Q_D(QQmlRoleSorter);
92 d->m_roleNameValidated = false;
93}
94
95QT_END_NAMESPACE
96
97#include "moc_qqmlrolesorter_p.cpp"