Accessing QObject class properties which is stored in QList
Unsolved
QML and Qt Quick
-
Hello, I am having trouble in accessing a property in QML.
QList<ClassB> is a property and i am able to access that but when i try to access the properties of classB in QML i am getting type error/Undefined. Following is the code:
#include <QObject> #include "classb.h" Q_DECLARE_METATYPE(QList<ClassB*>) class ClassA : public QObject { Q_OBJECT Q_PROPERTY(QList<ClassB*> objList READ getClassBDetails) public: explicit ClassA(QObject *parent = nullptr); QList<ClassB *>getClassBDetails(); private: QList<ClassB*> m_list; ClassB m_Bobj; };
#include "classa.h" ClassA::ClassA(QObject *parent) : QObject(parent) { m_list.append(&m_Bobj); } QList<ClassB *> ClassA ::getClassBDetails() { return m_list; }
#include <QObject> class ClassB : public QObject { Q_OBJECT Q_PROPERTY(int val READ getval WRITE setval NOTIFY valChanged) public: explicit ClassB(QObject *parent = nullptr); int m_val = 10; int getval(); void setval(int val); signals: void valChanged(); public slots: };
#include "classb.h" ClassB::ClassB(QObject *parent) : QObject(parent) { } int ClassB::getval() { return m_val; } void ClassB::setval(int val) { m_val = val; emit valChanged(); }
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "classa.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); ClassA aObj; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("classAObj",&aObj); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
import QtQuick 2.6 import QtQuick.Window 2.2 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") Component.onCompleted: { console.log("value========",classAObj.objList[0].val) } }
If i try to access
"classAObj.objList[0].val"
i am gettingTypeError: Cannot read property 'val' of undefined
error. What is that i am doing wrong here ? -
Hi,
You didn't registrer ClassB to be used by QML.
-
ClassB, you are using it in a property.
By the way, why not use QObjectList and a Q_INVOKABLE method ? Might be more straightforward.
More information on how to integrate CPP with QML here.