Home > Net >  How to create a QML component from C with component scope instance hierarchy
How to create a QML component from C with component scope instance hierarchy

Time:10-03

I have a test QML file like this:

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

And I want to dynamically create and assign the innerItem at runtime from C (I am trying to setup a testing framework). Here is what I have in 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();

But ComponentToBeTested doesn't seem to be able to see x_SCALE and y_SCALE defined in TestMain. What am I missing here?

CodePudding user response:

This is due to missing QQmlContext.
I would need to create the QML instance passing the context:

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

  • Related