我有一个用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++代码中)是无效的,因此该解决方案将不起作用。

有任何想法吗?

最佳答案

我根据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();
}

07-24 09:28