Using QStandardItemModel in QML
Article Metadata
Code Example
Article
QStandardItemModel is a highly convenient class when you want to enjoy both the ease of use of QListWidget, and the ability to co-operate with classes that need a proper QAbstractItemModel instance. There is no shame in not wanting to create your own application specific subclass of QAbstractItemModel if you don't need huge models.
However, QStandardItemModel is pretty useless when interfacing with QML, because you can't set "role names" for it directly (so that e.g. Qt::UserRole + 1 would refer to role 'bookTitle'), and as such the class can't be used directly in your QML delegates. RoleItemModel to the rescue! It provides lower level of pain than the other mechanisms [1] for pushing your data to QML: Custom subclass of QAbstractItemModel and QList<QObject*>. There is no magic in RoleItemModel - it merely calls QAbstractItemModel::setRoleNames, which happens to be a protected member of QAbstractItemModel.
Copy RoleItemModel to your project from: File:Roleitemmodel.zip
Example usage:
Enumerate the role ID's somewhere:
struct RedditEntry {
enum RedditRoles {
UrlRole = Qt::UserRole + 1,
DescRole,
...
};
...
}
Instantiate the class
QHash<int, QByteArray> roleNames;
roleNames[RedditEntry::DescRole] = "desc";
roleNames[RedditEntry::ScoreRole] = "score";
m_linksmodel = new RoleItemModel(roleNames);
Populate with data (i.e. QStandardItem instances with multiple attributes identified by role id)
QStandardItem* it = new QStandardItem();
it->setData(e.desc, RedditEntry::DescRole);
it->setData(e.score, RedditEntry::ScoreRole);
m_linksmodel->appendRow(it);
Expose to QML:
QDeclarativeContext *ctx = ...
ctx->setContextProperty("mdlLinks", m_linksmodel);
Use the model from QML in a Delegate for ListView, GridView, whatever:
Component {
id: mydelegate
Rectangle {
Text {
text: desc
}
Text {
text: score
}
}
}RoleItemModel also contains the following static convenience function:
QVariantMap getModelData(const QAbstractItemModel* mdl, int row)
This allows you to dump contents of a particular row to QVariantMap (the values keyed by role names), to address debugging purposes or genuine need.


(no comments yet)