如何将 QML 项目分配给 QML 中的组件属性,然后在组件内使用该对象? [英] How do you assign a QML Item to a component property in QML and then use that object inside the component?

查看:19
本文介绍了如何将 QML 项目分配给 QML 中的组件属性,然后在组件内使用该对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 QML 对象,该对象的作用类似于其他对象的包装器.这是我的 QML 文件 (Container.qml):

I'm trying to create a QML object that acts like a wrapper for other objects. Here's my QML file (Container.qml):

Item {
    property string label
    property Item control

    Row {
        Label {
            text: label
        }

        // Not sure how to display the control assigned to the control property
    }
}

我想做的事情(在我使用这个组件的 QML 中)是这样的:

What I would like to do (in my QML that consumes this component) is something like this:

Container {
    label: "My Label"
    control: Textbox {
        text: "My Value"
    }
}

当输入该 QML 时,结果(在界面中)应该类似于该 QML 的输出:

When fed that QML the result (in the interface) should be something resembling the output from this QML:

Item {
    Row {
        Label {
            text: "My Label"
        }
        Textbox {
            text: "My Value"
        }
    }
}

这可能吗?当我尝试这样做时,在将项目分配给控件属性时,我得到无法将对象分配给属性".我搜索了 Qt 论坛并无情地用谷歌搜索,但没有成功.如果有人知道答案,将不胜感激.

Is this possible? When I try to do this I get "cannot assign object to property" when assigning an Item to the control property. I've searched the Qt forums and Googled this mercilessly, but no success. If anybody knows the answer it would be greatly appreciated.

谢谢

杰克

推荐答案

您可以使用 Loader 元素,然后将 'control' 属性设置为 alias 直接引用加载器的 sourceComponent 属性.

You can dynamically load items using the Loader element, and then set the 'control' property to be an alias that directly refers to the loader's sourceComponent property.

所以您的 Container.qml 可能如下所示:

So your Container.qml could look like this:

Item {
    property string label
    property alias control : loader.sourceComponent

    width: 200; height: 200

    Row {
        Label { text: label }
        Loader { id: loader }
    }
}

现在,当您将图形项分配给控件"属性时,加载器将自动显示它.

Now when you assign a graphical item to the 'control' property, it will automatically be displayed by the Loader.

这篇关于如何将 QML 项目分配给 QML 中的组件属性,然后在组件内使用该对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆