Solved 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
QML
Text{ //text: myModel2.mystr.name1 // this works text: myModel2.lstr[0].name1 y: sensor.width + 5 font.family: "Helvetica" font.pointSize: 10 anchors.horizontalCenter: parent.horizontalCenter }
C++
test.h
#ifndef TEST_H #define TEST_H #include <QObject> struct MyStruct { Q_GADGET // Q_OBJECT int m_val; public: 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) }; Q_DECLARE_METATYPE(MyStruct); class test : public QObject { Q_OBJECT Q_PROPERTY(MyStruct mystr READ getMyStruct WRITE setMyStruct NOTIFY myStructChanged) Q_PROPERTY(QList<MyStruct> lstr READ getLstr WRITE setLstr NOTIFY lstrChanged) public: 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(); } signals: void myStructChanged(); void lstrChanged(); public slots: }; #endif // TEST_H
test.cpp
#include "test.h" test::test(QObject *parent) : QObject(parent) { MyStruct l_value; l_value.m_name1 = "b1"; l_value.m_name2 = "b2"; setMyStruct(l_value); QList<MyStruct> l_strList; l_strList.append(l_value); setLstr(l_strList); }
-
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 theQ_DECLARE_METATYPE(MyStruct);
-
this works with Qt5.14
please upgrade your Qt version if it is possible