如何正确引用parent的parent?
How to refer to the parent of the parent correctly?
有一个元素 FlowChart
,其属性为 p1
、p2
、p3
... pn
。
SensorValuesSetter
必须能够使用位于其中深处的元素 Button
访问这些属性。
我想象这样的解决方案:
// main.qml
// ...
FlowChart {
id: flowChart
anchors.fill: parent
SensorValuesSetter {
id: valueSetterWindow
}
// ...
}
// SensorValuesSetter.qml
ApplicationWindow {
id: valueSetterWindow
// ...
GridLayout {
// ...
Label { text: "Давление 1: "; Layout.fillWidth:true; }
ValueInputField { id: p1_val_field; }
Label { text: "Давление 2: "; Layout.fillWidth:true; }
ValueInputField { id: p2_val_field; }
// ....
Button {
id: button
text: qsTr("Применить")
onPressed: {
valueSetterWindow.parent.p1.value = Number.fromLocaleString(p1_val_field.text)
valueSetterWindow.parent.p2.value = Number.fromLocaleString(p2_val_field.text)
// ...
}
}
但在这种情况下会出现错误 TypeError: Cannot read property 'p1' of undefined
或 TypeError: Cannot read property 'p1' of undefined
。
你能解释一下这是什么问题吗?我想线索是我试图以错误的方式引用 parent 的 parent。
ApplicationWindow
不是 Item
因此没有 属性 parent
.
您可以依赖动态范围 (see more on the scopes here)
或者您在新 属性:
中显式传递 parent
// SensorValuesSetter.qml
ApplicationWindow {
property Item parent // Add the missing property. Maybe some other name...
[...]
}
以及实例化它的位置:
SomeItem {
id: myItem
SensorValuesSetter {
parent: myItem // Set it explicitly
}
}
有一个元素 FlowChart
,其属性为 p1
、p2
、p3
... pn
。
SensorValuesSetter
必须能够使用位于其中深处的元素 Button
访问这些属性。
我想象这样的解决方案:
// main.qml
// ...
FlowChart {
id: flowChart
anchors.fill: parent
SensorValuesSetter {
id: valueSetterWindow
}
// ...
}
// SensorValuesSetter.qml
ApplicationWindow {
id: valueSetterWindow
// ...
GridLayout {
// ...
Label { text: "Давление 1: "; Layout.fillWidth:true; }
ValueInputField { id: p1_val_field; }
Label { text: "Давление 2: "; Layout.fillWidth:true; }
ValueInputField { id: p2_val_field; }
// ....
Button {
id: button
text: qsTr("Применить")
onPressed: {
valueSetterWindow.parent.p1.value = Number.fromLocaleString(p1_val_field.text)
valueSetterWindow.parent.p2.value = Number.fromLocaleString(p2_val_field.text)
// ...
}
}
但在这种情况下会出现错误 TypeError: Cannot read property 'p1' of undefined
或 TypeError: Cannot read property 'p1' of undefined
。
你能解释一下这是什么问题吗?我想线索是我试图以错误的方式引用 parent 的 parent。
ApplicationWindow
不是 Item
因此没有 属性 parent
.
您可以依赖动态范围 (see more on the scopes here)
或者您在新 属性:
中显式传递 parent// SensorValuesSetter.qml
ApplicationWindow {
property Item parent // Add the missing property. Maybe some other name...
[...]
}
以及实例化它的位置:
SomeItem {
id: myItem
SensorValuesSetter {
parent: myItem // Set it explicitly
}
}