【发布时间】:2019-08-14 00:15:25
【问题描述】:
在从其父组件外部引用项目的属性时,我可能会收到“无法分配给不存在的属性”错误,这似乎取决于某些编译时操作顺序。
我创建了一个小型示例应用程序,它展示了为该属性分配颜色的一些不同方法,其中直接分配失败,但对默认属性的类似分配有效,甚至以后分配有效。
这是我的 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 的文件在同一个目录中:
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.background 颜色而不需要单独的文件或等到运行时?
【问题讨论】: