在 QML 文件之间共享对象

2022-01-19 00:00:00 qt qml c++

我是 QML 编码的新手,我正在尝试编写我的第一个 Sailfish OS 应用程序.对于后端,我创建了一个 C++ 类.但是,我想实例化该 C++ 类的一个对象,并在封面和主页(两个单独的 QML 文件)中使用它,这样我就可以处理存储在该类中的相同数据.如何在单独的 QML 文件中处理相同的对象?

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?

推荐答案

您可以使对象在 QtQuick 上下文中可用:

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"; }
};

在 main.cpp 中

in main.cpp

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

在 QML 中的任何地方:

and from anywhere in QML:

console.log(sharedObject.mySharedSlot())

如果你不想让它在 QML 中全局",你可以稍微封装一下,只需创建另一个 QObject 派生类,注册它以在 QML 中实例化并拥有其中的一个属性返回指向该对象实例的指针,这样它仅在您实例化访问器"QML 对象时可用.

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
};

在 main.cpp 中

in main.cpp

MySharedObject obj;
qRegisterMetaType<MySharedObject*>();

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

在 QML 中

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

相关文章