将属性传递给QML Loader创建的对象 [英] Pass properties to object created by QML Loader
问题描述
我有一个加载另一个qml的QML Loader
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的ID
,width
,height
等?
How can I pass parameters to set the ID
, width
, height
and so on of the loaded qml?
推荐答案
方法1: 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});
请注意,您无法设置
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
对象上设置width
和height
,并在horizontalBarGauge.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/horizontalBarGauge.qml:
qrc:/Gauges/horizontalBarGauge.qml:
Item {
anchors.fill: parent
}
这篇关于将属性传递给QML Loader创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!