Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

loading QML file as a component from C++ to QQmlApplicationEngine



  • Hello everyone,

    I am trying to load a qml file to my QQmlApplicationEngine. I guess, since the component is visual item(rect), somehow, engine does not render it.
    Can someone please point me where am i missing?

    Thank you.

    Here is my sample code,

    /* MyItem.qml */
    import QtQuick 2.5
     
    Rectangle {
        id: top
        property string str: "#FF0000"
        color: str
        width: 10
        height: 20
        Component.onCompleted: console.log("myitem ctor", width, height, x, y, visible, color);
    }
     
    /* main.qml */
    import QtQuick 2.5
    import QtQuick.Window 2.2
     
    Window {
        visible: true
        id: root
     
        MouseArea {
            id: mouse
            anchors.fill: parent
            onClicked: {
                Qt.quit();
            }
        }
     
        Text {
            id: text
            text: qsTr("Hello World")
            anchors.centerIn: parent
        }
    }
     
    /* main.cpp */
    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QQmlComponent>
    #include <QQmlEngine>
     
    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
     
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
     
        QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/MyItem.qml")));
     
        QObject *childItem = component.create();
        QList<QObject *> rootObjects = engine.rootObjects();
        QObject *parentItem = rootObjects.first();
     
        childItem->setParent(parentItem);
     
        QQmlEngine::setObjectOwnership(childItem, QQmlEngine::CppOwnership);
     
        return app.exec();
    }

  • Moderators

    @kafanti You need to set a visual parent using setParentItem. And this parent being the Window's invisible root item which you can get using contentItem. So something like this:

    QQuickItem *parentItem = qvariant_cast<QQuickItem*>(rootObjects.first()->property("contentItem"));
    childItem->setParentItem(parentItem); 
    

    Also cast childItem to QQuickItem instead of QObject to get access to setParentItem.


Log in to reply