动态创建的自定义 QML 对象不可见

Dynamically created Custom QML object not visible

我有一个名为 "Cell.qml" 的自定义 QML 项目,我想将其动态插入到我的根 window 中并使其可见。我还尝试更改 z 属性,但我无法修复它,该对象仍然不可见(即使 root->dumpObjectTree() 的输出表明该对象作为根的子项存在 window)

这是执行代码后的结果

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

root->dumpObjectTree() 的输出;:

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

setParent()设置non-visual、QObjectparent会员。 QQuickItem还有一个属性,parentItem也就是QML中的parentQQuickItem属性,就是那个属性需要进行设置,以便对象在视觉上显示。