ebeglary
ebeglary

Reputation: 84

QML Animation: How to stop infinite animation in exact position?

I'm trying to stop infinite animation from function where position is known. I need animation to animate until the x = pos and then to stop.

NumberAnimation on x {
        id : animationObject
        loops: Animation.Infinite
        from: 0
        to: 500
        running: true
        duration: 3000
}

I have tried to stop it in this way, but it doesn't help.

function stop(pos) {
     animationObject.loops = 1;
     animationObject.to = pos;
}

Upvotes: 0

Views: 821

Answers (1)

Dimitry Ernot
Dimitry Ernot

Reputation: 6584

You can set an expression as value of the property running to be true if the position is not reached and false otherwise.

The x property is also associated to the signal onXChanged that will be triggered each time the item moved. You can also use it if you don't want/can't change the animation definition:

Rectangle {
    anchors.fill: parent
    Rectangle {
        id: rect
        width: 100
        height: 100
        color: "red"

        property int bound: 50
        NumberAnimation on x {
                  id : animationObject
                  loops: Animation.Infinite
                  from: 0
                  to: 100
                  running: Math.abs(rect.x - bound) > 1
                  duration: 3000
        }
        onXChanged: console.log(rect.x, Math.abs(rect.x - bound) > 1)
    }
}

In the code above, the animation will be stopped when the rectangle reachs the X coordinate defined by the property bound.

As the value will be a floated number, we can't use the equality and have to use a margin error (1 in my code).

Upvotes: 1

Related Questions