c++qtqmlqqmlcomponentqqmlapplicationengine

Dynamically created Custom QML object not visible


I have a custom QML item called "Cell.qml" which I'd like to insert dynamically in my root window and make it visible. I also tried changing the z property, but I couldn't fix it, the object is still invisible (even tough the output of root->dumpObjectTree() says the object exists as a child of the root window)

This is the result after executing the code

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

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


    QObject *root = engine.rootObjects()[0];
    QQmlComponent component(&engine, "qrc:/Cell.qml");
    if (component.isReady()){
        QObject *object = component.create();
        object->setParent(root);
        engine.setObjectOwnership(object, engine.CppOwnership);
    }
    root->dumpObjectTree();

    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
}

Cell.qml

import QtQuick 2.0
import QtQuick.Controls 2.3

Item{
    property string txt: ""
    property color c: "#d4ccc4"
    visible: true
    z:20
Rectangle {
    width: 75; height: 75
    color: c
    visible: true
    radius : 3
    scale : 1
    z:10
Text{
    anchors.centerIn: parent
    text: txt
    font.family: "Helvetica"
    font.pointSize: 20
    color: "white"
    }
}
}

Output of root->dumpObjectTree();:

QQuickWindowQmlImpl::
   QQuickRootItem:: 
    Cell_QMLTYPE_0:: 
        QQuickRectangle:: 
            QQuickText:: 

Solution

  • setParent() sets a non-visual, QObject level parent member. QQuickItem has another property, parentItem which is the parent QQuickItem property in QML, it is that property that needs to be set so the object appears visually.