Split object between QML files

I am new to QML coding and am trying to write my first Sailfish OS application. For the backend, I created one C ++ class. However, I want to create an instance of one object of this C ++ class and use it both on the cover and on the main page (two separate QML files), so I can work with the same data that is stored in this class. How to address the same object in separate QML files?

+5
source share
1 answer

You can make an object available in the context of QtQuick:

class MySharedObject : public QObject { Q_OBJECT public: MySharedObject(QObject * p = 0) : QObject(p) {} public slots: QString mySharedSlot() { return "blablabla"; } }; 

in main.cpp

 MySharedObject obj; view.rootContext()->setContextProperty("sharedObject", &obj); 

and from anywhere in QML:

 console.log(sharedObject.mySharedSlot()) 

If you do not want it to be "global" in QML, you can encapsulate it a bit, just create another derived QObject class, register it to create an instance in QML and get the property returns a pointer to this object instance in it, so it will be only available where you instantiate the QML "accessor" object.

 class SharedObjAccessor : public QObject { Q_OBJECT Q_PROPERTY(MySharedObject * sharedObject READ sharedObject) public: SharedObjAccessor(QObject * p = 0) : QObject(p) {} MySharedObject * sharedObject() { return _obj; } static void setSharedObject(MySharedObject * obj) { _obj = obj; } private: static MySharedObject * _obj; // remember to init in the cpp file }; 

in main.cpp

 MySharedObject obj; qRegisterMetaType<MySharedObject*>(); SharedObjAccessor::setSharedObject(&obj); qmlRegisterType<SharedObjAccessor>("Test", 1, 0, "SharedObjAccessor"); 

and in QML

 import Test 1.0 ... SharedObjAccessor { id: acc } ... console.log(acc.sharedObject.mySharedSlot()) 
+7
source

Source: https://habr.com/ru/post/1206350/


All Articles