Important: Please read the Qt Code of Conduct -

How to access QList of struct members in qml

  • Hi,
    I need to know how to acess the members of struct from qlist in qml.

    Currently i can acess only the members of struct in qml and i am also able to acess simple qlist i.e. Qlist made of qString.

    But the problem starts when i try to acess the members of struct embedded in qlist.

    I have created a struct (MyStruct) in c++ and can acscess it in Qml. I can also acess QList ( which is QStrinList).

    But problem comes when i am trying to access QList. it gives me the error

    qrc:/OrderBar.qml:26: TypeError: Cannot read property 'name1' of undefined

    the Codes are


            //text: myModel2.mystr.name1  // this works
            text: myModel2.lstr[0].name1
            y: sensor.width + 5
            font.pointSize: 10
            anchors.horizontalCenter: parent.horizontalCenter



    #ifndef TEST_H
    #define TEST_H
    #include <QObject>
    struct MyStruct {
       // Q_OBJECT
        int m_val;
        QString m_name1;
        QString m_name2;
        QString m_name3;
        QString m_name4;
        Q_PROPERTY(int val MEMBER m_val)
        Q_PROPERTY(QString name1 MEMBER m_name1)
        Q_PROPERTY(QString name2 MEMBER m_name2)
        Q_PROPERTY(QString name3 MEMBER m_name3)
        Q_PROPERTY(QString name4 MEMBER m_name4)
    class test : public QObject
        Q_PROPERTY(MyStruct mystr READ getMyStruct
                   WRITE setMyStruct NOTIFY myStructChanged)
        Q_PROPERTY(QList<MyStruct> lstr READ getLstr
                   WRITE setLstr NOTIFY lstrChanged)
        explicit test(QObject *parent = nullptr);
        MyStruct strObj;
        MyStruct getMyStruct() const
            return strObj;
        void setMyStruct(MyStruct val)
            strObj = val;
            emit myStructChanged();
        QList<MyStruct> strList;
        QList<MyStruct>  getLstr() const
            return strList;
        void setLstr(QList<MyStruct> val)
            strList = val;
            emit lstrChanged();
        void myStructChanged();
        void lstrChanged();
    public slots:
    #endif // TEST_H


    #include "test.h"
    test::test(QObject *parent) : QObject(parent)
        MyStruct l_value;
        l_value.m_name1 = "b1";
        l_value.m_name2 = "b2";
         QList<MyStruct> l_strList;

  • @Mandeep-Chaudhary

    I'm not an expert when it comes to QML but I think you need to register your struct as MetaType (Otherwise QML doesnt know about your structs structure and variables)
    Edit: I missed the Q_DECLARE_METATYPE(MyStruct);

  • this works with Qt5.14
    please upgrade your Qt version if it is possible

Log in to reply