我有一个QML Loader
可以加载另一个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
等?
最佳答案
方法1: Loader::setSource
您可以使用 Loader::setSource(url source, object properties)
函数在构造过程中设置属性,例如:
gaugeLoader.setSource("qrc:/Gauges/horizontalBarGauge.qml", {"width": 100, "height": 100});
请注意,您不能以这种方式设置
id
attribute,因为它不是普通的属性属性: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.
相反,您可以按如下方式创建属性别名:
property alias gauge: gaugeLoader.item
方法2:相对于Loader对象的几何
或者,您可以在
width
对象上设置height
和Loader
,并指定horizontalBarGauge.qml
相对于其父对象(即Loader
对象)的宽度和高度。property alias gauge: gaugeLoader.item
Loader {
id: gaugeLoader
width: 100
height: 100
}
qrc:/Gauges/horizontalBarGauge.qml:
Item {
anchors.fill: parent
}
关于qt - 如何将属性传递给Loader创建的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44271158/