[SOLVED] How to use multiple different list element in ListView

  • I can use different properties in ListElement when using QML model. The following code works properly. Arg2 is only in the first ListElement:

    ListView  {
        height: 200
        Layout.fillWidth: true
        delegate: Rectangle {
            height: 50
            Label {
                anchors.fill: parent
                text: arg1 + " " + (arg2 === undefined ? "" : " " + arg2)
        model: ListModel {
            ListElement { arg1: "Elem1"; arg2: "Elem1arg2" }
            ListElement { arg1: "Elem2" }

    But I'd like to load model from C++. I have multiple inherited classes.

    Here is base idea of my classes:

    class Class1 : public QObject
      Q_PROPERTY(QString arg1...
    class Class2 : public Class1
      Q_PROPERTY(QStirng arg2...

    I tried to use QObjectList -based model. I didn't get it working because only properties from Class1 are available:

    QList<QObject*> list;
    list.append(new Class1("Elem1"));
    list.append(new Class2("Elem2","Elem2arg1" ));
    return QVariant::fromValue(list);

    How I can get properties from both classes? Or is it even possible?

  • Moderators

    @jimcad AFAIK it should work. All the parent's properties should be visible to child.
    Have you set the inherited property's value from child ?

  • @p3c0 Yes, arg1 is set for both and it's visible in QML. But arg2 is available only in Class2 and it's not visible in QML. That is the problem.

  • Moderators

    @jimcad OfCourse how would arg2 be available to Class1 ? Children inherit properties of their parents and not the other way.
    You can add a check there something like:

    Text {
        text : typeof model.modelData.arg2==="undefined" ? "DefaultValue" : model.modelData.arg2

  • @p3c0 Yes, I know that. There must be something wrong in my code because this not working either:

        MyClass1{ id: class1 }
        MyClass2{ id: class2 }
        Component.onCompleted: {
            class2.arg1 = "Changed arg1"
            console.log(class2.arg1) // works ok
            class2.arg2 = "Changed arg2" // <-- Doesn't work        

    Seems that all properties from inherited classes doesn't works. Here is my example project: https://www.dropbox.com/s/mi33b8ml8nctrup/qml-test.zip?dl=0

  • @p3c0 I found it. It was missing Q_OBJECT macro in Class2. Now it works properly. Thanks for your advice.

Log in to reply

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