2
votes

Suppose on C++ side I've created a QList<QObject *> myObjects which contains several custom objects derived from QObject.

And then expose it to QML by setContextProperty( "myModel", QVariant::fromValue( myObjects ) );

The question is, in my QML code, how can I get and use a specific element (by index) in myModel (which is a QList). For instance, I would like to take a random element from the list and show it?

The example is here: http://doc.qt.io/qt-5/qtquick-models-objectlistmodel-example.html, where all elements of the model are shown in a ListView`, while I just want to show one (or several) of them.

2
QML transparently support QList<> types as described in this document. So C++ array will be converted to common JavaScript array. See it herefolibis
so simple and basic question but this is a necessary question. so +1 :)S.M.Mousavi

2 Answers

5
votes

its pretty easy...

to get item number i from the model:

myModel[i]

and to access its properties/roles:

myModel[i].propertyName
3
votes

To get an item from the list you can use the [] operator:

myModel[index]

The elements of a QList are similar to arrays in javascript since QML is based on the latter.

The following example shows getting the names in random form (it only replaces the code in the example).

view.qml

import QtQuick 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls 1.4

//![0]

ColumnLayout{
    ListView {
        width: 100; height: 100

        model: myModel
        delegate: Rectangle {
            height: 25
            width: 100
            color: model.modelData.color
            Text {
                text: name
            }
        }


    }

    Button {
        text: "random"
        onClicked: {
            t.text = myModel[ Math.floor(Math.random()*myModel.length)].name;
        }
    }
    Text{
        id: t
        text: ""
    }
}