[solved] Access to custom CPP object
-
Hi,
I have an application with one part develop with Cpp and one part with QML. The first part enable to get data from database and the QML part display result. I search the best way to get the data. I've tried to use Q_PROPERTY and qmlRegisterType without succeed.
When I run the app, I see "my object [object Object] undefined" and the "onMyObjectChanged" seems not be activated;main.cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include "myapp.h" #include <QQmlContext> #include <QQmlComponent> #include "myobject.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); MyApp *myApp = new MyApp(); context->setContextProperty("myLib", myApp); qmlRegisterType<MyObject>("Test", 1, 0, "MyCppObject"); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
myapp.h
#ifndef MYAPP_H #define MYAPP_H #include <QObject> #include "QDebug" #include "myobject.h" class MyApp : public QObject { Q_OBJECT Q_PROPERTY(MyObject* monObjet READ myObject NOTIFY myObjectChanged) public: explicit MyApp(QObject *parent = 0); Q_INVOKABLE void action(); MyObject* myObject(); signals: void myObjectChanged(); private : MyObject *m_myObject; }; #endif // MYAPP_H@
myapp.cpp
#include "myapp.h" MyApp::MyApp(QObject *parent) : QObject(parent) { } void MyApp::action(){ m_myObject = new MyObject(this); m_myObject->setName("myName"); emit myObjectChanged(); } MyObject* MyApp::myObject() { return m_myObject; }
myobject.h
#ifndef MYOBJECT_H #define MYOBJECT_H #include <QObject> class MyObject : public QObject { Q_OBJECT Q_PROPERTY(QString name READ getName) public: explicit MyObject(QObject *parent = 0); QString getName() const; void setName(const QString &value); private : QString name; }; #endif // MYOBJECT_H@
myobject.cpp
#include "myobject.h" MyObject::MyObject(QObject *parent) : QObject(parent) { } QString MyObject::getName() const { return name; } void MyObject::setName(const QString &value) { name = value; }
and main.qml
import QtQuick 2.2 import QtQuick.Window 2.1 import Test 1.0 Window { visible: true width: 360 height: 360 property variant myObject: MyCppObject MouseArea { anchors.fill: parent onClicked: { myLib.action() console.log("my object ", MyCppObject, MyCppObject.name) } } Text { text: MyCppObject.name anchors.centerIn: parent } onMyObjectChanged: console.log("myObjectChanged ", myObject, myObject.name) }
-
@helenebro You need to instantiate it. For eg.
MyCppObject { id: cppObj } property variant myObject: cppObj onMyObjectChanged: console.log("myObjectChanged ", myObject, myObject.name)