【问题标题】:Dynamically created Custom QML object not visible动态创建的自定义 QML 对象不可见
【发布时间】:2018-09-07 10:05:56
【问题描述】:

我有一个名为“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的输出->dumpObjectTree();:

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

【问题讨论】:

  • 请注意,绝对没有充分的理由从 C++ 创建 QML 对象。相反的情况更为常见。

标签: c++ qt qml qqmlcomponent qqmlapplicationengine


【解决方案1】:

setParent() 设置一个非可视的QObject 级别parent 成员。 QQuickItem 有另一个属性,parentItem,它是 QML 中的 parent QQuickItem 属性,需要设置该属性才能使对象在视觉上显示。

【讨论】:

  • 不确定我是否误解了答案,但我必须设置parent 属性:object-&gt;setProperty("parent", QVariant::fromValue&lt;QObject*&gt;(gridLayout))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 2015-12-07
  • 2014-12-22
  • 2021-08-10
相关资源
最近更新 更多