4

假设我有一个为子项使用别名的 TestComponent.qml。组件文件如下所示:

测试组件.qml

import QtQuick 2.5
Column {
    default property alias children: cont.children;

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

输出是:

header
body
footer
body1

有没有办法让别名对于动态组件的创建也是透明的?理想情况下不使用 C++。

4

1 回答 1

2

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

测试组件.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
于 2015-10-16T02:22:24.520 回答