Qt 如何将子项动态附加到具有子项别名的QML项
假设我有一个TestComponent.qml,它对子项使用别名。组件文件如下所示: TestComponent.qmlQt 如何将子项动态附加到具有子项别名的QML项,qt,qml,alias,default,createobject,Qt,Qml,Alias,Default,Createobject,假设我有一个TestComponent.qml,它对子项使用别名。组件文件如下所示: TestComponent.qml import QtQuick 2.5 Column { default property alias children: cont.children; Text { text: "header" } Column { id: cont } Text { text: "footer
import QtQuick 2.5
Column {
default property alias children: cont.children;
Text {
text: "header"
}
Column {
id: cont
}
Text {
text: "footer"
}
}
import QtQuick 2.5
Column {
default property alias children: cont.children;
property alias childCont: cont
Text {
text: "header"
}
Column {
id: cont
}
Text {
text: "footer"
}
}
然后我有一个主文件,在那里我实例化了组件。如果通过静态组件实例化添加子组件文本,它将按预期显示在页眉和页脚之间。但是,如果动态添加子组件,它将忽略子别名并在页脚后添加子组件。该文件如下所示:
main.qml
import QtQuick 2.5
import QtQuick.Controls 1.4
ApplicationWindow {
visible: true
width: 200
height: 200
TestComponent {
id: t1
Text {
text: "body"
}
}
Component {
id: txt
Text {
text: "body1"
}
}
Component.onCompleted: {
txt.createObject(t1)
}
}
import QtQuick 2.5
import QtQuick.Controls 1.4
ApplicationWindow {
visible: true
width: 200
height: 200
TestComponent {
id: t1
Text {
text: "body"
}
}
Component {
id: txt
Text {
text: "body1"
}
}
Component.onCompleted: {
txt.createObject(t1.childCont)
}
}
输出为:
header
body
footer
body1
有没有办法使别名对动态组件创建也是透明的?理想情况下,不使用C++。< p>它不回答问题,但是绕过这个问题的方法可能是,通过属性别名使组件中的预期父项可访问,并将其用作CealObjt函数调用中的父参数。这是密码 TestComponent.qml
import QtQuick 2.5
Column {
default property alias children: cont.children;
Text {
text: "header"
}
Column {
id: cont
}
Text {
text: "footer"
}
}
import QtQuick 2.5
Column {
default property alias children: cont.children;
property alias childCont: cont
Text {
text: "header"
}
Column {
id: cont
}
Text {
text: "footer"
}
}
main.qml
import QtQuick 2.5
import QtQuick.Controls 1.4
ApplicationWindow {
visible: true
width: 200
height: 200
TestComponent {
id: t1
Text {
text: "body"
}
}
Component {
id: txt
Text {
text: "body1"
}
}
Component.onCompleted: {
txt.createObject(t1)
}
}
import QtQuick 2.5
import QtQuick.Controls 1.4
ApplicationWindow {
visible: true
width: 200
height: 200
TestComponent {
id: t1
Text {
text: "body"
}
}
Component {
id: txt
Text {
text: "body1"
}
}
Component.onCompleted: {
txt.createObject(t1.childCont)
}
}
输出:
header
body
body1
footer