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

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c++ - Share an object between QML files

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

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

1 Answer

0 votes
by (71.8m points)

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...