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

C++ 动态创建的自定义QML对象不可见,c++,qt,qml,qqmlcomponent,qqmlapplicationengine,C++,Qt,Qml,Qqmlcomponent,Qqmlapplicationengine,我有一个名为Cell.QML的定制QML项,我想在我的根窗口中动态插入它并使其可见。我还尝试更改z属性,但无法修复它,即使root->dumpObjectTree的输出显示该对象作为根窗口的子对象存在,该对象仍然不可见 这是执行代码后的结果 main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlComponent> int main(int arg

我有一个名为Cell.QML的定制QML项,我想在我的根窗口中动态插入它并使其可见。我还尝试更改z属性,但无法修复它,即使root->dumpObjectTree的输出显示该对象作为根窗口的子对象存在,该对象仍然不可见

这是执行代码后的结果

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();
}
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"
    }
}
}
根->转储对象树的输出;:

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

setParent设置非可视、QObject级别的父成员。QQuickItem还有另一个属性parentItem,它是QML中的父QQuickItem属性,需要设置该属性以使对象直观显示。

setParent设置一个非可视的QObject级父成员。QQuC++有另一个属性,PalTimeTM是QML中的父QQuiType属性,它是需要设置的属性,因此对象会出现在视觉上。相反的是更常见的。注意,没有完全的理由来从C++创建QML对象。相反的情况更常见。不确定我是否误解了答案,但我必须设置父属性:object->setPropertyparent,QVariant::fromValuegridLayout不确定我是否误解了答案,但我必须设置父属性:object->setPropertyparent,QVariant::fromValuegridLayout
QQuickWindowQmlImpl::
   QQuickRootItem:: 
    Cell_QMLTYPE_0:: 
        QQuickRectangle:: 
            QQuickText::