1

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:: 
4

1 回答 1

6

setParent()设置一个非可视的QObject级别parent成员。QQuickItem还有另一个属性,parentItemparent QQuickItemQML 中的属性,它是需要设置的属性,以便对象在视觉上显示。

于 2018-03-28T16:08:12.777 回答