如何从具有组件范围实例层次结构的 C++ 创建 QML 组件

How to create a QML component from C++ with component scope instance hierarchy

我有一个这样的测试 QML 文件:

// TestMain.qml
import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    id: root

    width: G_WIDTH
    height: G_HEIGHT

    readonly property real x_SCALE: width / G_WIDTH
    readonly property real y_SCALE: height / G_HEIGHT

    title: "Test Window"
    visible: true

    Item {
        id: wrapper

        anchors.fill: parent

        <innerItem>
    }
}

我想在运行时从 C++ 动态创建和分配 innerItem(我正在尝试设置测试框架)。这是我在 C++ 中的内容:

engine->load("TestMain.qml");
if (engine->rootObjects().isEmpty()) { // Error }

auto root = engine->rootObjects().first();
auto wrapper = qobject_cast<QQuickItem*>(main->children()[1]);
QQmlComponent component(engine.get(), "ComponentToBeTested.qml");
auto item = qobject_cast<QQuickItem*>(component.createWithInitialProperties(props));
item->setParentItem(wrapper);
item->setSize(wrapper->size());

app->exec();

但是ComponentToBeTested似乎看不到TestMain中定义的x_SCALEy_SCALE。我在这里错过了什么?

这是由于缺少 QQmlContext
我需要创建传递上下文的 QML 实例:

item = qobject_cast<QQuickItem*>(
    component.createWithInitialProperties(
        props,
        engine.contextForObject(wrapper)));