如何从名称作为字符串访问 qml 属性?

时间:2021-07-16 12:52:00

标签: qml qt-quick

我的问题与 QML Access object property by property name string 非常相似,只是我想访问根属性...

我希望能够做到这一点:

Rectangle {
    property string color1: "blue"
    property string color2: "red"
    property string curColor : "color1"

    color: /*something like*/ currentScope[curColor]
}

注意:这是一个 MWE,我知道在这种情况下有更聪明的方法。我的用例是提供一个简单易用的 Adapter,它需要知道它必须作用于哪个属性。我知道绑定,但它需要和 id...我想避免使用显式 id 并在当前范围内工作。

1 个答案:

答案 0 :(得分:0)

您只需为您的 Rectangle 提供一个 ID,以便您可以引用它。

Rectangle {
    id: root
    property string color1: "blue"
    property string color2: "red"
    property string curColor : "color1"

    color: root[curColor]
}

更新: 要在没有 id 的情况下执行此操作,您可以使用 this 指针。它在 documentation 中,但不容易找到。

Rectangle {
    property string color1: "blue"
    property string color2: "red"
    property string curColor : "color1"

    color: this[curColor]
}