File indexing completed on 2024-04-28 03:56:15

0001 /*
0002  *   SPDX-FileCopyrightText: 2023 ivan tkachenko <me@ratijas.tk>
0003  *
0004  *   SPDX-License-Identifier: LGPL-2.0-or-later
0005  */
0006 
0007 #include "krolenames.h"
0008 
0009 #include <QAbstractItemModel>
0010 #include <QQmlInfo>
0011 
0012 class KRoleNamesPrivate
0013 {
0014     KRoleNames *const q;
0015 
0016 public:
0017     explicit KRoleNamesPrivate(KRoleNames *qq)
0018         : q(qq)
0019     {
0020     }
0021 
0022     QHash<int, QByteArray> roleNames() const;
0023     QAbstractItemModel *model() const;
0024 };
0025 
0026 KRoleNames::KRoleNames(QObject *parent)
0027     : QObject(parent)
0028     , d(new KRoleNamesPrivate(this))
0029 {
0030     Q_ASSERT(parent);
0031     if (!d->model()) {
0032         qmlWarning(parent) << "KRoleNames must be attached to a QAbstractItemModel";
0033         return;
0034     }
0035 }
0036 
0037 KRoleNames::~KRoleNames() = default;
0038 
0039 QByteArray KRoleNames::roleName(int role) const
0040 {
0041     const auto map = d->roleNames();
0042     return map.value(role, QByteArray());
0043 }
0044 
0045 int KRoleNames::role(const QByteArray &roleName) const
0046 {
0047     const auto map = d->roleNames();
0048     return map.key(roleName, -1);
0049 }
0050 
0051 KRoleNames *KRoleNames::qmlAttachedProperties(QObject *object)
0052 {
0053     return new KRoleNames(object);
0054 }
0055 
0056 QHash<int, QByteArray> KRoleNamesPrivate::roleNames() const
0057 {
0058     if (const auto m = model()) {
0059         return m->roleNames();
0060     }
0061     return {};
0062 }
0063 
0064 QAbstractItemModel *KRoleNamesPrivate::model() const
0065 {
0066     return qobject_cast<QAbstractItemModel *>(q->parent());
0067 }
0068 
0069 #include "moc_krolenames.cpp"