Data Models Deconstructed - Part 1: QML / JS Arrays
Qt provides many different methods of exposing data and using data in QML Model Views, i.e. the ListView, PathView, or GridView
Over this many part series of posts, we will investigate the many methods of exposing data to QML views – starting from the simplest, to the most complex.
QML / Javascript Array
The simplest method is using a Javascript array to feed primitive type-based data into a ListView.
All QML delegates inside a model view contain a model
property that represents the data for that particular index in the data model array.
In this example, the data model is a JS array – therefore, the data is available directly through the modelData
property of the model
object.
Qt documentation uses magic to demonstrate this. They use modelData
directly since this pointer is available as a context property of the delegate. It is optional to reference the color value using model.modelData
but it is more verbose to a bystander reading the code.
import QtQuick 2.5
Item {
id: root
property var colors: ["red", "white", "blue"]
width: 640; height: 480
ListView {
id: _listView
anchors.fill: parent
model: root.colors
delegate: Rectangle {
id: _rectangleDelegate
width: ListView.view.width
height: ListView.view.height / 3
// Use the colors array to change
// the color of this Rectangle
color: model.modelData
// Many times developers misuse
// model views by accessing the array
// directly, i.e.
// color: root.colors[model.index]
// or
// color: root.colors[index]
}
}
}