首页 > 解决方案 > QML 中有没有办法更改多个事件的按钮颜色?

问题描述

我是 Qml 的新手,我有点迷茫。我想为图像或按钮的颜色设置多个状态。一个更简单的部分是,如果按下按钮,它应该改变颜色或图像。这可以通过以下方式实现:

Button {
    width: 50
    height: 50

    background: Rectangle {
        color: parent.pressed ? "red" : "blue"
    }
}

在 Addtion 中,我还有状态:单击、启用、启用单击等等。

所以首先:我可以在没有 else 语句的情况下捕获 parent.pressed,例如:

if (parent.pressed)
    color = "red"
elseif (onClicked)
    color = "blue"
....

当我的后端禁用或启用我的任何 GUI 元素时,可能会设置其他状态,我可以要求并更改我的颜色。

所以基本上我有两个问题:如何在 if 语句中捕获事件以及如何捕获多个事件而不使用 if else 语句,例如:

 parent.pressed ? "red" : "blue"

我更进一步,可以添加状态。

Button {
width: 50
height: 50
id: btn
onClicked: state="clicked"
onPressed: state="pressed"

background: Rectangle
{
    anchors.fill: parent
}

states: [
    State {
        name: "clicked"
        PropertyChanges { target: btn; background: color= "red" }
    },
    State {
        name: "pressed"
        PropertyChanges { target: btn; background: color= "blue" }
    }
]

}

但这不会改变我的按钮的颜色,而是 UI 的其余部分。

标签: qtqml

解决方案


我猜你的代码中有语法错误。实际上它应该类似于以下内容:

Button {
    id: btn
    text: "Click me"
    property color bgColor
    anchors.centerIn: parent
    state: pressed ? "pressed" : "regular"
    background: Rectangle {
        color: btn.bgColor
    }

    states: [
        State {
            name: "regular"
            PropertyChanges {
                target: btn
                bgColor: "orange"

            }
        },
        State {
            name: "pressed"
            PropertyChanges {
                target: btn
                bgColor: "green"
            }
        }
    ]
}

或者你可以玩Rectangle

background: Rectangle {
    id: bg        
}

states: [
    State {
        name: "regular"
        PropertyChanges {
            target: bg
            color: "orange"

        }
    },
    State {
        name: "pressed"
        PropertyChanges {
            target: bg
            color: "green"
        }
    }
]

推荐阅读