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

时间:2018-03-28 16:04:40

标签: c++ qt qml qqmlcomponent qqmlapplicationengine

我有一个名为" 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();
}

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-&gt; dumpObjectTree();:

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

1 个答案:

答案 0 :(得分:4)

setParent()设置了一个非可视的QObjectparent成员。 QQuickItem有另一个属性parentItem,它是QML中的parent QQuickItem属性,需要设置该属性才能使对象以可视方式显示。