如何将属性传递给 Loader 创建的对象? [英] How to pass properties to a Loader created object?

查看:22
本文介绍了如何将属性传递给 Loader 创建的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QML Loader 可以加载另一个 qml

I have a QML Loader which loads another qml

Loader { id: gaugeLoader }

PieMenu {
    id: pieMenu

    MenuItem {
        text: "Add Bar Gauge"
        onTriggered: gaugeLoader.source = "qrc:/Gauges/horizontalBarGauge.qml"
    }
    MenuItem {
        text: "Action 2"
        onTriggered: print("Action 2")
    }
    MenuItem {
        text: "Action 3"
        onTriggered: print("Action 3")
    }
}

如何通过参数设置加载的qml的IDwidthheight等?

How can I pass parameters to set the ID, width, height and so on of the loaded qml?

推荐答案

方法一: Loader::setSource

您可以使用 Loader::setSource(url source, object properties)函数在构造时设置属性,例如:

You can use the Loader::setSource(url source, object properties) function to set the properties during construction, for example:

gaugeLoader.setSource("qrc:/Gauges/horizontalBarGauge.qml", {"width": 100, "height": 100});

请注意,您不能设置 id属性这样写,因为它不是一个普通的属性属性:

Note that you cannot set the id attribute in this way, because it is a not an ordinary property attribute:

一旦创建了一个对象实例,它的 id 属性的值无法更改.虽然它可能看起来像一个普通的属性,但 id属性不是普通的属性属性,有特殊的语义适用于它;例如,无法访问 myTextInput.id在上面的例子中.

Once an object instance is created, the value of its id attribute cannot be changed. While it may look like an ordinary property, the id attribute is not an ordinary property attribute, and special semantics apply to it; for example, it is not possible to access myTextInput.id in the above example.

相反,您可以按如下方式创建属性别名:

Instead, you can create a property alias as follows:

property alias gauge: gaugeLoader.item

方法2:相对于Loader对象的几何体

Method 2: geometry relative to Loader object

作为替代方案,您可以在 Loader 对象上设置 widthheight 并在 horizo​​ntalBarGauge 中指定宽度和高度.qml 相对于其父对象,即 Loader 对象.

As an alternative, you can set the width and height on the Loader object and specify the width and height in horizontalBarGauge.qml relative to its parent, i.e. the Loader object.

property alias gauge: gaugeLoader.item
Loader { 
    id: gaugeLoader 
    width: 100
    height: 100
}

qrc:/Gauges/horizo​​ntalBarGauge.qml:

qrc:/Gauges/horizontalBarGauge.qml:

Item {
    anchors.fill: parent
}

这篇关于如何将属性传递给 Loader 创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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