QML: C++ Model with different (derived) objects. Is it possible?



  • Hi,

    I have a QList<QObject*> which I use as a model in QML. The objects I put there have some Q_PROPERTY. So lets assume we have a class MarkGUI and a derived class ProtocolMarkGui with some additional properties. Is it possible to mix MarkGui and ProtocolMarkGui objects in the QList I use as model, and use different delegates for the different objects?


  • Moderators

    @maxwell31 said in QML: C++ Model with different (derived) objects. Is it possible?:

    Is it possible to mix MarkGui and ProtocolMarkGui objects in the QList I use as model,

    Yes. QList<MarkGui*> will accept both MarkGui and ProtocolMarkGui objects. And QML won't complain, either.

    and use different delegates for the different objects?

    That's possible. Let's assume you have some property called isProtocol which returns true in ProtocolMarkGui but false in MarkGui. Then:

    delegate: Loader {
      source: "qrc:/" + isProtocol? "ProtocolDelegate.qml" : "Delegate.qml"
    }
    

    You should be able to get at your model data even inside the loader. If not, then try with modelData property, or pass the data via properties.

    There are other ways to do it, too - all depends on what kind of delegates you need.



  • I seem to have a problem with getting the properties of the derived class into to loader, while the base class works well in the loader. I do it the following way:

            delegate: Loader { // loader choosing the right component
                property double timeStart: model.timeStart
                property string timeEnd: model.timeEnd
                // but the property from the derived class
                property string derivedClassProperty: model.test // does not work


  • It'll be easier to debug if you can share a minimal code sample for this (maybe a repo on GitHub or something).


  • Qt Champions 2017

    what is model ? what is test ? how did you expose the model to QML ? Please show your class hierarchy as well & properties you have defined.


  • Moderators

    The property for accessing model data is called modelData, not model. Perhaps that is the issue.



  • I will post a minimal example, might need some time though



  • Actually, you don't need anything before the property name

    property double timeStart: timeStart
    property string timeEnd: timeEnd
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.