How to implement QML ListModel like get method for an QAbstractListModel derived model

avb picture avb · Mar 28, 2014 · Viewed 19.4k times · Source

I want to use an QAbstractListModel derived model in QML. Binding the model to views already works great.

The next thing I want achieve is the ability to access specific items and their role like it is possible with a QML ListModel

grid.model.get(index).DisplayRole

But I have no idea how to implement this get method in my QAbstractListModel derived model.

Any hints?

Answer

labsin picture labsin · Sep 3, 2014

You can add an Q_INVOKABLE function to the QAbstractItemModel derived class like this:

...

Q_INVOKABLE QVariantMap get(int row);

...

QVariantMap get(int row) {
    QHash<int,QByteArray> names = roleNames();
    QHashIterator<int, QByteArray> i(names);
    QVariantMap res;
    while (i.hasNext()) {
        i.next();
        QModelIndex idx = index(row, 0);
        QVariant data = idx.data(i.key());
        res[i.value()] = data;
        //cout << i.key() << ": " << i.value() << endl;
    }
    return res;
}

This will return something like { "bookTitle" : QVariant("Bible"), "year" : QVariant(-2000) } so you could use .bookTitle on it