4x10
4x10

Reputation: 43

use a QList<QVariantMap> as a model for a QML ListView

I can't figure out how to use a QList as a model. There are several examples where the data type is one dimensional but haven't seen something nested like this. Relevant code below:

main.cpp - here i register the QList

viewer.rootContext()->setContextProperty("productlist", QVariant::fromValue(databaseController.listProjects()) );

main.qml - here i want to use the model 'productlist'

ListView {
    id: list_view

    anchors.fill: parent
    model: productlist
    delegate:
        Rectangle{
           height: 20
           width: 200
           color: "#CCCCCC"
           Text { text:  modelData.name }
        }
}

Note, if I use databaseController.listProjects()[0] I can get the first QVariantMap of course and the example works, though I am not sure how to iterate over the values and/or keys.

I'm using QtQuick 2.0 and Qt 5

I have read something about QAbstractListModel but can't figure out how to use it.. am I on the right track there or is there an easier way?

thanks for your help

Upvotes: 1

Views: 8030

Answers (1)

TheBootroo
TheBootroo

Reputation: 7518

You can easily use a QVariantList as a model for a ListView, though you need to know that it's going to be read-only, as the value() of QVariantList/QVariantMap is const :

QVariantList myModel;
foreach (QVariantMap item, databaseController.listProjects()) {
    myModel.append (item);
}

viewer.rootContext()->setContextProperty("productlist", QVariant::fromValue(myModel));

And it's done !

Upvotes: 5

Related Questions