在QML文件之间共享对象 [英] Share an object between QML files

查看:472
本文介绍了在QML文件之间共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是QML编码的新手,我正在尝试编写我的第一个Sailfish OS应用程序。对于后端,我创建了一个C ++类。但是,我想实例化该C ++类的一个对象,并在Cover和主页(两个单独的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

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

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

这篇关于在QML文件之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆