[solved]How can I register C++ class to QML?
-
@p3c0
I want to make the source form ① to ② as follows.
①
int main(int argc, char *argv[]){
QApplication app(argc, argv);
qmlRegisterType<A>("MyLib", 1, 0, "A");
qmlRegisterType<B>("MyLib", 1, 0, "B");
qmlRegisterType<C>("MyLib", 1, 0, "C");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/form/main.qml")));
return app.exec();
}
②
int main(int argc, char *argv[]){
QApplication app(argc, argv);
qmlRegisterType<ALL>("MyLib", 1, 0, "ALL");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/form/main.qml")));
return app.exec();
}class ALL is used to get objects of class A, B ,C.
-
@beidaochuan Ok. Not sure. But what approach did you follow to get that error you posted earlier ?
-
@p3c0
I just modified the class ALL as follows.// .h class ALL : public QObject { Q_OBJECT public: explicit ALL(QObject *parent = 0); Q_PROPERTY(A* bmA READ bmA NOTIFY bmAChanged) Q_INVOKABLE A *bmA(); Q_PROPERTY(B* bmB READ bmB NOTIFY bmBChanged) Q_INVOKABLE B *bmB(); Q_PROPERTY(C* bmC READ bmC NOTIFY bmCChanged) Q_INVOKABLE C *bmA(); private: A *a; B * b; C *c; signals: void bmAChanged(); void bmBChanged(); void bmCChanged(); public slots: }; //.cpp ALL::ALL(QObject *parent) : QObject(parent) { a = new A(this); b = new B(this); c = new C(this); } A *ALL::bmA() { return a; } B *ALL::bmB() { return b; } C *ALL::bmC() { return c; }
-
@p3c0
when I ran the project, the errors happend.QMetaProperty::read: Unable to handle unregistered datatype 'A*' for property 'ALL::bmA'
QMetaProperty::read: Unable to handle unregistered datatype 'B*' for property 'ALL::bmB'
QMetaProperty::read: Unable to handle unregistered datatype 'C*' for property 'ALL::bmC' -
@beidaochuan To make pointers available in
Q_PROPERTY
you will need to register it first as:qRegisterMetaType<A*>("A*");
Then since it is declared as a property no need to make the accessor
Q_INVOKABLE
. So//In cpp Q_PROPERTY(A* bmA READ bmA NOTIFY bmAChanged) A *MyClass::bmA() const { return a; } private: A* a; //In QML //Access it as usual property All { id: all } console.log(all.bmA) //should get A object.
-
@p3c0
Thanks a lot.
That means I must register class A,B,C and class ALL to QML, and just manager A,B,C with class ALL.
In QML I can use like this:
ALL {id: all}
all.bmA
all.bmB
all.bmCthat is right?
-
@beidaochuan Class A,B and C as:
qRegisterMetaType<A*>("A*"); qRegisterMetaType<B*>("B*");
to make pointers available
And class ALL as usual usingqmlRegisterType
qmlRegisterType<ALL>("ALL", 1, 0, "ALL");
In QML I can use like this:
ALL {id: all}
all.bmA
all.bmB
all.bmCthat is right?
Right.
-
@p3c0
It's very kind of you.
Thank you very much. -
@beidaochuan Glad that I was helpful :)
Please mark the post as [Solved] if done. -