Access roles without naming it in QAbstractListModel. How?
Solved
General and Desktop
-
Hello all!
Is there any way to access roles in QAbstractListModel without naming it? I mean something like access to array[index]:public: enum Roles { Role0 = Qt::UserRole + 1, Role1, Role2, Role3, ... }; ... QHash<int, QByteArray> roleNames() const { QHash<int, QByteArray> roles = QAbstractListModel::roleNames(); roles[Role0] = "Role0"; roles[Role1] = "Role1"; roles[Role2] = "Role2"; roles[Role3] = "Role3"; ... return roles; }
In this example defined exact roles in model. I want to create universal model where I can access to it by something like position-index in array. Is there any way to make it possible? Or at least update roleNames dynamically via variable or parameter in class. Something like example below.
*.h file:
public: explicit ATableViewModel(QObject *parent = nullptr); virtual ~ATableViewModel(void); QHash<int, QByteArray> roleNames() const; private: QHash<int, QByteArray> pRoleNames = {};
*.cpp
QHash<int, QByteArray> ATableViewModel::roleNames() const { return pRoleNames; }
-
You can use a 1-dimensional role and fill it with a JSON object, document or array which gives you even more flexibility than a single array.
https://doc.qt.io/qt-5/qvariant.html#toJsonObject -
@AxelVienna said in Access roles without naming it in QAbstractListModel. How?:
Thx. Issue closed. Example published.