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

4
假设我有一个名为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,它会如预期地出现在头部和底部之间。但是,如果我动态添加子组件,则忽略children别名并将子组件添加到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)
    }
}

输出结果为:
header
body
footer
body1

有没有一种方法能够使别名对于动态组件的创建也透明呢?最好不要使用C++。
1个回答

2

这与问题无关,但解决方法是通过属性别名使组件中预期的父项可访问,并将其用作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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接