Multsens
Multsens

Reputation: 75

Is there a way in QML to change a buttons color on multiple events?

I am new to Qml and I am a little bit lost. I want to set multiple states for an Image, or a color of a button. One simpler part is, that if the button is pressed, it should change color or image. This can be achieved by the following:

Button {
    width: 50
    height: 50

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

In Addtion I have also the states: clicked, enabled, enabled clicked and many more.

So first: Can I do just catch the parent.pressed without an else statement, something like:

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

and maybe setting additional states, which I can ask for and change my color, when my backend is disabling or enabling any of my GUI elements.

So basically I have two problems: how to catch a event in an if statement and how to catch multiple events and not using that if else statement like:

 parent.pressed ? "red" : "blue"

I got further, it is possible to add states.

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" }
    }
]

}

But this won't change the color of my button, but the rest of the UI.

Upvotes: 0

Views: 1911

Answers (1)

folibis
folibis

Reputation: 12864

I guess you have syntax error in your code. Actually it should be something like the following:

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"
            }
        }
    ]
}

or you can play with the Rectangle:

background: Rectangle {
    id: bg        
}

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

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

Upvotes: 2

Related Questions