【问题标题】:How to access a qml property from its name as a string?如何从其名称作为字符串访问 qml 属性?
【发布时间】:2021-07-16 12:52:00
【问题描述】:

我的问题与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,我知道在这种情况下有更聪明的方法。我的用例是提供一个简单易用的适配器,它需要知道它必须作用于哪个属性。我知道 Binding,但它需要和 id...我想避免使用显式 id 并在当前范围内工作。

【问题讨论】:

    标签: qml qt-quick


    【解决方案1】:

    您只需为您的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]
    }
    

    【讨论】:

    • 并且我明确指出我不想添加一个 id 来加快编写代码的速度......因为该组件实际上将用作子适配器>。
    • 我想我应该一直读到最后。但我不明白为什么避免使用 id 会加快速度。
    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2016-01-16
    相关资源
    最近更新 更多