1 c++ qt qml qqmlcomponent qqmlapplicationengine
我有一个名为“Cell.qml”的自定义 QML 项目,我想将其动态插入到我的根窗口中并使其可见。我也尝试更改 z 属性,但我无法修复它,该对象仍然不可见(即使 root->dumpObjectTree() 的输出也表明该对象作为根窗口的子窗口存在)
这是执行代码后的结果

主程序
#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();
}
Run Code Online (Sandbox Code Playgroud)
主文件
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
}
Run Code Online (Sandbox Code Playgroud)
细胞.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"
}
}
}
Run Code Online (Sandbox Code Playgroud)
root->dumpObjectTree(); 的输出:
QQuickWindowQmlImpl::
QQuickRootItem::
Cell_QMLTYPE_0::
QQuickRectangle::
QQuickText::
Run Code Online (Sandbox Code Playgroud)
setParent()设置一个非可视化的QObject级别parent成员。QQuickItem有另一个属性,parentItem它是parent QQuickItemQML 中的属性,它是需要设置的属性,以便对象在视觉上出现。
| 归档时间: |
|
| 查看次数: |
940 次 |
| 最近记录: |