在从父组件之外引用项的属性时,我可以得到一个“不能分配给不存在的属性”错误,这个错误似乎取决于某些编译时的操作顺序。
我已经创建了一个小示例应用程序,它展示了为该属性分配颜色的一些方法,其中直接赋值失败,但是类似于默认属性的赋值工作,甚至是以后的赋值工作。
这是我的main.qml:
import QtQuick 2.7
import QtQuick.Window 2.12
Window {
id: application_window
visible: true
width: 640
height: 480
Thing {
// colors.backgroundColor: "red" // Direct assignment of custom property: Fails
// thing.color: "red" // Direct assignment of default property: Works
// Component.onCompleted: colors.backgroundColor = "red" // Run time assignment of custom property: Works
}
}
和一个名为Thing.qml的文件在同一个dir中:
Item {
id: root
height: 50
width: 50
property alias colors: colors
property alias thing: thing
Rectangle {
id: thing
anchors.fill: root
color: colors.backgroundColor
}
Item {
id: colors
property color backgroundColor: "blue"
}
}
通过单独取消对main.qml中的行的注释,您可以看到直接赋值colors.backgroundColor不起作用,但是更改颜色的其他方法确实有效,甚至在运行时分配colors.backgroundColor。我还将“colors”项移到了另一个文件中,该文件允许直接赋值(在本例中,我猜backgroundColor被认为是一个默认属性)。是否有任何方法可以直接分配colors.background颜色,而不需要单独的文件或等待运行时?
发布于 2019-08-13 23:51:34
是否有任何方法可以直接分配colors.background颜色,而不需要单独的文件或等待运行时?
不是的。
当您以声明方式设置(在绑定的左侧使用)一个子属性(分组属性的属性)( foo.bar
)时,QML引擎只能在foo
的类型具有bar
属性的情况下才能这样做。
在您的示例中,在执行thing.color
时,thing
的类型是Rectangle
,因此它有一个color
属性。在执行colors.backgroundColor
时,我猜colors
的类型是Item
,而不是Thing.qml中定义的隐式类型。
当您在另一个文件中创建“colors”项时,QML引擎知道该对象的显式类型,然后绑定工作。
有人可能会说,引擎可以为别名属性使用隐式类型,但我不确定它是否正确,您实际上是在向外部公开内联实现细节。
您可以随时打开一个bug,至少是为了澄清事情,即使行为没有改变。
https://stackoverflow.com/questions/57486723
复制相似问题