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())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…