从C ++ QML类型访问QML根对象

时间:2017-12-04 09:07:43

标签: c++ qt qml

我有一个用C ++编写的自定义QML类型,类名是 MyCustomType ,它位于文件 mycustomtype.h mycustomtype.cpp

main.cpp 文件中,QML类型可用:

qmlRegisterType<MyCustomType>("MyCustomType", 1, 0, "MyCustomType");

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("../qml/main.qml")));

main.cpp 文件中,我可以像这样访问引擎的根对象:

rootObject = static_cast<QQuickWindow *> (engine.rootObjects().first());

我的问题是我需要从 mycustomtype.cpp 文件中的MyCustomType类中访问该rootObject。这可能吗?

我能想到的唯一方法是将rootObject传递给构造函数。但由于MyCustomType在QML文档中实例化,而不是在C ++代码中,因此该解决方案不起作用。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我找到了一个基于GrecKo评论的解决方案。

我没有使MyCustomType扩展QObject,而是扩展了QQuickItem。然后可以从该类中的任何位置调用window()并获取根对象。这很简单,也很有效。

<强> mycustomtype.h:

class MyCustomType : public QQuickItem
{
    Q_OBJECT

public:
    explicit MyCustomType(QQuickItem *parent = 0);

}

<强> mycustomtype.cpp

MyCustomType::MyCustomType(QQuickItem *parent) : QQuickItem(parent)
{
    QQuickWindow *rootObject = window();    
}

答案 1 :(得分:0)

方法1:传递根对象

您可以使用setContextProperty在QML中全局提供变量:

engine.rootContext ().setContextProperty("rootObject", QVariant::fromValue(engine.rootObjects().first()));

现在,您可以使用rootObject访问QML中的根对象,并在构建期间将其传递给MyCustomType

方法2:使根对象静态可用

您可以使根对象静态可用。一个干净的解决方案是创建一个包含所有全局数据成员的单例类。