Using a QAbstractListModel of C++ structs with QML
-
Hi,
I currently have a list model inheriting from QAbstractListModel that holds a QList of C++ structs. How would I go about using this model with QML?
It seems logical to me to structure the model this way, i.e., having a list of struct objects instead of say a table model where each column represents one of the struct's members, but is this "wrong" when thinking about QML?
I understand that QML is unable to use C++ structs directly, not even if I declare the struct with Q_DECLARE_METATYPE. I tried creating a QObject class instead of a struct, where each data member is a Q_PROPERTY, but had trouble with precisely Q_DECLARE_METATYPE as it requires a copy constructor, and that is disabled for QObjects (?).
What would be the best practise QML friendly way to create a model holding several structs?
-
@Obi-Wan said in Using a QAbstractListModel of C++ structs with QML:
What would be the best practise QML friendly way to create a model holding several structs?
QML doesn't need to know anything about the struct types directly. It's enough to abstract them via the model roles.
See this how to use C++ item-models in QML.
Most important here is the roleNames() method. -
@raven-worx Thanks!
I've read that page several times, but only now realized that I could use the roles this way. I had the impression that roles were more about displaying the same data in different contexts, and were not for "selecting" different data from a model. I guess I'm struggling a bit with the concept of roles. The usage doesn't quite feel coherent between Widgets and QML?
My undestanding is now that there is no problem having a QList of structs in a QAbstractListModel, I just have to give QML some kind of name to call, and then define, in the C++ data()-method, what happens when QML wants to access data using that name. The index will take care of which of the structs is being used by QML and the roles will take care of which stuct elements are returned to QML.