问题描述
我有一个 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的ID
、width
、height
等?
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在上面的例子中.
相反,您可以按如下方式创建属性别名:
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
}
这篇关于如何将属性传递给 Loader 创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!