How to access elements stored in QAbstractListmodel in QML (delegates), other than using element roles?

I just want to display items from a list using QML, but not using the roles of the elements. E.g. I want to call the getName () method, which returns the name of the displayed item.

Is it possible? I did not find anything clear answer to this.

+4
source share
1 answer

You can use one special role to return the entire item, as you can see below:

template<typename T> class List : public QAbstractListModel { public: explicit List(const QString &itemRoleName, QObject *parent = 0) : QAbstractListModel(parent) { QHash<int, QByteArray> roles; roles[Qt::UserRole] = QByteArray(itemRoleName.toAscii()); setRoleNames(roles); } void insert(int where, T *item) { Q_ASSERT(item); if (!item) return; // This is very important to prevent items to be garbage collected in JS!!! QDeclarativeEngine::setObjectOwnership(item, QDeclarativeEngine::CppOwnership); item->setParent(this); beginInsertRows(QModelIndex(), where, where); items_.insert(where, item); endInsertRows(); } public: // QAbstractItemModel int rowCount(const QModelIndex &parent = QModelIndex()) const { Q_UNUSED(parent); return items_.count(); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { if (index.row() < 0 || index.row() >= items_.count()) { return QVariant(); } if (Qt::UserRole == role) { QObject *item = items_[index.row()]; return QVariant::fromValue(item); } return QVariant(); } protected: QList<T*> items_; }; 

Remember to use QDeclarativeEngine :: setObjectOwnership in all of your insertion methods. Otherwise, all of your objects returned from the data method will collect garbage on the QML side.

+8
source

All Articles