Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm new to coding in QML and I'm trying to write my first Sailfish OS app. For the backend I have created one C++ class. However, I want to instantiate one object of that C++ class and use it both in the Cover and the main Page (two separate QML files), so I can work with the same data, stored in that class. How do address that same object in the separate QML files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
243 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can make the object available in the QtQuick context:

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 don't want to have it "global" in QML, you can go about a little to encapsulate it, just create another QObject derived class, register it to instantiate in QML and have a property in it that returns a pointer to that object instance, this way it will be available only where you instantiate the "accessor" QML 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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...