【问题标题】:Custom properties don't exist at compile time? "Cannot assign to non-existent property"编译时不存在自定义属性? “不能分配给不存在的财产”
【发布时间】: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 颜色而不需要单独的文件或等到运行时?

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    有没有办法直接分配colors.background颜色而不需要单独的文件或等到运行时?

    没有。

    当您以声明方式设置(在绑定的左侧使用它)像foo.bar 这样的子属性(分组属性的属性)时,QML 引擎只能在foo 的类型具有bar 属性。

    在你做thing.color的例子中,thing的类型是Rectangle,所以它确实有一个color属性。 在做colors.backgroundColor的时候,我猜colors的类型是Item而不是Thing.qml中定义的隐式类型。

    当您在不同的文件中创建“颜色”项时,QML 引擎会知道对象的显式类型,然后绑定就会起作用。

    有人可能会争辩说,引擎可以为别名属性使用隐式类型,但我不确定这是否正确,您实际上是在向外部公开内联实现细节。

    即使行为没有改变,您也可以随时打开一个错误,至少可以澄清一些事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2021-10-22
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多