I am trying to implement a nested comment system in a QML interface. I have a model in C++ (subclassed from QAbstractListModel) in which each item in the model returns two value
I have found this very useful article that helped to solve the problem https://lemirep.wordpress.com/2013/04/06/a-practical-case-exposing-qt-c-models-to-qml/.
The approach consists into creating another ListModel (derived from QAbstracListModel) inside the model class. In my example, I replace QVariantMap dataMap()
with another ListModel dataModel()
. Notice that this requires other changes too (which can be found at the link provided)
I am currently working on an application, which requires the visualization of isolated branches of massive (hundreds of millions of objects) tree. Since it is a tree, it is very similar to your problem, which is about nested models.
My solution was to make a form of abstraction. Since the tree already exists and is a completely different design layer than the GUI, I use a proxy object, which contains the model class, which attaches to the visualized tree node. The model is just an adapter for the list view to access the underlying data.
The model provides an "object" and a "type" role, which the "root" delegate uses to instantiate a UI element for the children nodes, and the object role is used to create a proxy to attach to each child, so effectively, I get indirectly nested models.
Each delegate is basically a loader (not a Loader
QML element though), which receives a pointer to every object and its type from the model roles, so it creates a proxy for that type, and a UI element type + ".qml"
attached to the proxy as its data source.
I cannot share any code, but hopefully you get the picture. This approach sounds a little complicated, but it offers several huge advantages: