Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Using QStandardItemModel in QML

From Wiki
Jump to: navigation, search
Article Metadata
Code ExampleCompatibility
Created: vivainio (01 Nov 2010)
Last edited: hamishwillee (11 Oct 2012)

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:

Example usage:

Enumerate the role ID's somewhere:

struct RedditEntry {
enum RedditRoles {
UrlRole = Qt::UserRole + 1,

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);

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.

This page was last modified on 11 October 2012, at 01:20.
116 page views in the last 30 days.