如何动态地将子项附加到具有子项的别名的QML项

时间:2015-10-16 02:22:25

标签: qml alias default dynamically-generated 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"
    }
}

然后我有一个主文件,在那里我实例化组件。如果通过静态组件实例化添加子组件Text,它将按预期显示在页眉和页脚之间。但是,如果我动态添加子组件,它会忽略子别名并将子项添加到页脚之后。该文件如下所示:

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)
    }
}

输出结果为:

header
body
footer
body1

有没有办法以别名对动态组件创建透明的方式进行?理想情况下不使用C ++。

1 个答案:

答案 0 :(得分:0)

它没有回答这个问题,但是解决这个问题的方法可能是,通过属性别名访问组件中的预期父项,并将其用作createObject函数调用中的父参数。这是代码

TestComponent.qml

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.childCont)
    }
}

输出:

header
body
body1
footer