首页 > 解决方案 > 将一个 qml 中定义的组件加载到另一个 qml

问题描述

我创建了一个组件,如下所示。我的问题是:使用加载器我在一个 qml 中加载 textComponent。我也可以在任何其他 qml 文件中加载 textComponent 吗?如果是,那么如何加载这种类型的组件?

    Item {
    id: window
    width: parent.width
    height: parent.height * 0.21

    property Component textComponent: Item {
        id: txtComp
        width: window.width * 0.80
        height: window.height * 0.16

        RowLayout {
            anchors.centerIn: parent
            spacing: 10
            Text {
                text: defaultText
                color: "white"
            }
        }

 Rectangle {
        id: background
        width: parent.width
        height: parent.height
        color: "black"

        Loader {
            id: textComponentLoader
            width: textComponent.width
            height: textComponent.height
            sourceComponent: textComponent
        }
    }

注意:使用内联组件我收到错误,如屏幕截图所示:

在此处输入图像描述 在此处输入图像描述

标签: qtqml

解决方案


@folibis 的答案很可能是您想要做的,但我想指出您可以将组件作为其他对象的属性访问,就像您访问任何其他属性一样。您已经将组件定义为属性,如下所示:

// SomeObject.qml
Item {
    property Component someComponent: Item {
        // 
    }
}

现在在您的另一个对象中,如果您有第一个对象的实例,您可以访问它的属性。

// SomeOtherObject.qml
Item {
    SomeObject {
        id: someObject
    }

    Loader {
        sourceComponent: someObject.someComponent
    }
}

推荐阅读