1/*
2 * SPDX-FileCopyrightText: 2023 ivan tkachenko <me@ratijas.tk>
3 *
4 * SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7#include "krolenames.h"
8
9#include <QAbstractItemModel>
10#include <QQmlInfo>
11
12class KRoleNamesPrivate
13{
14 KRoleNames *const q;
15
16public:
17 explicit KRoleNamesPrivate(KRoleNames *qq)
18 : q(qq)
19 {
20 }
21
22 QHash<int, QByteArray> roleNames() const;
23 QAbstractItemModel *model() const;
24};
25
26KRoleNames::KRoleNames(QObject *parent)
27 : QObject(parent)
28 , d(new KRoleNamesPrivate(this))
29{
30 Q_ASSERT(parent);
31 if (!d->model()) {
32 qmlWarning(me: parent) << "KRoleNames must be attached to a QAbstractItemModel";
33 return;
34 }
35}
36
37KRoleNames::~KRoleNames() = default;
38
39QByteArray KRoleNames::roleName(int role) const
40{
41 const auto map = d->roleNames();
42 return map.value(key: role, defaultValue: QByteArray());
43}
44
45int KRoleNames::role(const QByteArray &roleName) const
46{
47 const auto map = d->roleNames();
48 return map.key(value: roleName, defaultKey: -1);
49}
50
51KRoleNames *KRoleNames::qmlAttachedProperties(QObject *object)
52{
53 return new KRoleNames(object);
54}
55
56QHash<int, QByteArray> KRoleNamesPrivate::roleNames() const
57{
58 if (const auto m = model()) {
59 return m->roleNames();
60 }
61 return {};
62}
63
64QAbstractItemModel *KRoleNamesPrivate::model() const
65{
66 return qobject_cast<QAbstractItemModel *>(object: q->parent());
67}
68
69#include "moc_krolenames.cpp"
70

source code of kitemmodels/src/qml/krolenames.cpp