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.
source share