[Qt-qml] Exposing data model from C++
ari.koivisto at nokia.com
ari.koivisto at nokia.com
Wed Nov 24 09:55:52 CET 2010
Follow-up on my data model issue:
> On the QML + JS side I had a simple listmodel along the lines:
> ListModel {
> ListElement { start: "12:30"; ... ; legs: [ { type: "train"; id:
> "IC82"; ... }, ... ] }
> ListElement { start: "13:00"; ... ; legs: [ { type: "train"; id:
> "S62"; ... }, ... ] }
> }
>
> I can then visualize this using ListView and having a Repeater to go
> through the elements "legs" data. Resulting in something like this:
> | 1. Start: 12:30 ... | IC82 | ... |
> | 2. Start: 13:00 ... | S62 | ... |
...
> Now I'm not sure how to achieve the same functionality from C++ side.
...
> Documentation suggests using QAbstractItemModel and VisualDataModel,
> but that seems a bit overly complex? E.g. Could
> QAbstractListModel::data return an another QAbstractListModel that the
> Repeater could use directly?
I ended up trying CAbstractItemModel on the C++ side and VisualDataModel on the QML side. It took some trial and error to get the right hooks in place but here's how I did it:
1) C++ side: CAbstractItemModel inherited model that has logic built-in to the index method so it switches to right data set when rootIndex is changed from QML side
2) C++ side: data method logic to see what data set is been traversed and return the requested role data
3) QML Side: Nested VisualDataModels in ListView to build the visualization. Example:
ListView {
model: VisualDataModel {
id: firstDataModel
model: myModel
delegate: Rectangle {
Text { text: startTime }
...
Repeater {
model: VisualDataModel {
id: proxyModel
model: myModel
rootIndex: firstDataModel.modelIndex(index)
delegate:
Text { text: trainId }
}
}
...
}
A bit messy looking example (model, model, model, model :-)) but it works. Now I have the visualization I wanted, rows with a mash-up of data from two lists. Could the documentation be enhanced in this area? Some things took a while to understand when inheriting from CAbstractItemModel.
Regards,
Ari
More information about the Qt-qml
mailing list