Vladimír
Vladimír

Reputation: 759

QML: animation only when mouse enters image

I would like to make an animation when mouse comes over the image, but NOT when mouse leaves the image.

Item{
width: 800
height:800
Rectangle{
    id: blueRec
    width: 100; height: 100; color: "blue"
    MouseArea{
        anchors.fill: parent
        onClicked: {
            im1.visible = true
            im1.source = "1.png"
        }
    }
}
Image {
    id: im1
    scale: im1MouseArea.containsMouse ? 0.8 : 1.0
    Behavior on scale {
        NumberAnimation{
            id: anim
            from: 0.95
            to: 1
            duration: 400
            easing.type: Easing.OutBounce
        }
    }
    MouseArea{
        id: im1MouseArea
        hoverEnabled: true
        anchors.fill: parent
    }
}

}

The code above makes also animation, when mouse is leaving image.

Can someone help?

Upvotes: 4

Views: 1183

Answers (1)

MrEricSir
MrEricSir

Reputation: 8242

Setting the scale and then triggering an animation that alters the scale seems like an odd approach. If I were you, I'd break this out into states and set the animation to trigger on the appropriate transition.

Here's an example of how this could be done:

Image {
    id: im1

    states: [ "mouseIn", "mouseOut" ]
    state: "mouseOut"

    transitions: [
        Transition {
            from: "*"
            to: "mouseIn"
            NumberAnimation {
                target: im1
                properties: "scale"
                from: 0.95
                to: 1
                duration: 400
                easing.type: Easing.OutBounce
            }
        }
    ]

    MouseArea{
        id: im1MouseArea
        hoverEnabled: true
        anchors.fill: parent

        onContainsMouseChanged: {
            im1.state = containsMouse ? "mouseIn" : "mouseOut"
        }
    }
}

Upvotes: 5

Related Questions