在 qml 中绑定子 属性 的 属性
Binding property of child property in qml
我把它放在一个名为 ChildItem.qml
:
的文件中
Item{
property var childProperty
}
在另一个名为 ParentItem.qml
的文件中,我创建了父项并尝试将 childProperty
绑定到父项的 属性:
Item{
property ChildItem childItem: null
property var parentProperty
childItem.childProperty: parentProperty
}
在 main.qml
中,我实例化了两个对象并将父项的引用绑定到子项:
ApplicationWindow{
ChildItem{
id: childID
}
ParentItem{
id: parentID
childItem: childID
}
}
这让我在 childItem.childProperty: parentProperty
行出现 Cannot assign a value directly to a grouped property
错误。我通过如下更改父项来解决此问题:
Item {
property ChildItem childItem: null
property var parentProperty
//childItem.childProperty: parentProperty
onParentPropertyChanged: childItem.childProperty = parentProperty
}
但这看起来和感觉起来都很做作。是否有更好的方法或其他建议以其他方式更改结构?
好的,您的代码中有几个错误。逻辑的和句法的。
childItem.childProperty: parentProperty
此处不允许使用此行,因为混合了声明式代码和命令式代码。如果 childItem
为 null 又会怎样?将其替换为:
onChildItemChanged: {
if(childItem)
childItem.childProperty = parentProperty;
}
下一个错误:
childItem: childId
只需将 childId
替换为 childID
。
childItem.childProperty: parentProperty
不幸的是,这在 QML 语法中是不可能的,尽管它会很好。限制是绑定只能在元素本身的声明中定义,例如在本例中 ChildItem { ... }
。作为解决方法,Binding 元素可以用在其他地方:
Binding {
target: childItem
property: "childProperty"
value: parentProperty
}
但是,不可否认,这也很笨重。
我可能会首先尝试更改我的 QML 的结构以避免陷入这种情况,也许是这样的:
ApplicationWindow{
ChildItem{
id: childID
childProperty: parentID.parentProperty
}
ParentItem{
id: parentID
}
}
我把它放在一个名为 ChildItem.qml
:
Item{
property var childProperty
}
在另一个名为 ParentItem.qml
的文件中,我创建了父项并尝试将 childProperty
绑定到父项的 属性:
Item{
property ChildItem childItem: null
property var parentProperty
childItem.childProperty: parentProperty
}
在 main.qml
中,我实例化了两个对象并将父项的引用绑定到子项:
ApplicationWindow{
ChildItem{
id: childID
}
ParentItem{
id: parentID
childItem: childID
}
}
这让我在 childItem.childProperty: parentProperty
行出现 Cannot assign a value directly to a grouped property
错误。我通过如下更改父项来解决此问题:
Item {
property ChildItem childItem: null
property var parentProperty
//childItem.childProperty: parentProperty
onParentPropertyChanged: childItem.childProperty = parentProperty
}
但这看起来和感觉起来都很做作。是否有更好的方法或其他建议以其他方式更改结构?
好的,您的代码中有几个错误。逻辑的和句法的。
childItem.childProperty: parentProperty
此处不允许使用此行,因为混合了声明式代码和命令式代码。如果 childItem
为 null 又会怎样?将其替换为:
onChildItemChanged: {
if(childItem)
childItem.childProperty = parentProperty;
}
下一个错误:
childItem: childId
只需将 childId
替换为 childID
。
childItem.childProperty: parentProperty
不幸的是,这在 QML 语法中是不可能的,尽管它会很好。限制是绑定只能在元素本身的声明中定义,例如在本例中 ChildItem { ... }
。作为解决方法,Binding 元素可以用在其他地方:
Binding {
target: childItem
property: "childProperty"
value: parentProperty
}
但是,不可否认,这也很笨重。
我可能会首先尝试更改我的 QML 的结构以避免陷入这种情况,也许是这样的:
ApplicationWindow{
ChildItem{
id: childID
childProperty: parentID.parentProperty
}
ParentItem{
id: parentID
}
}