Bala Kumaran
Bala Kumaran

Reputation: 131

How to change a background image of a qml button while press and release

I need to change the background image of a Button while it is pressed. If I have a background image on the Button before it is pressed, I need to change that background image, when the Button is pressed, and then set it back to the original background image when the Button is released.

Here is my current code :

property bool bImgChange: true

Button {
    id: bu
    x: 121
    y: 40
    iconSource: "q.png"
    activeFocusOnPress: false
    opacity: 1
    checkable: true
    checked: true
    Layout.minimumWidth: 100
    Layout.minimumHeight: 100

    onClicked: {
        if ( bImgChange == true )
        {
            bu.iconSource = "index.png"
            bImgChange = false
        }
        else
        {
            bu.iconSource = "q.png"
            bImgChange = true
        }
    }
}

The above code only sets the background image while the Button is clicked whereas I need to change the background image on presses and releases.

Upvotes: 1

Views: 7056

Answers (1)

douyw
douyw

Reputation: 4074

Button has a property pressed which can be used like this:

Item {
    Image { source: btn.pressed? "image1.png" : "image2.png"; ...}
    Button { id: btn; ... }
}

or, if you want to change the iconSource of the Button, you can try something like this:

Button {
    iconSource: pressed? "image1.png" : "image2.png"
}

Hope it helps.

Upvotes: 5

Related Questions