QML动画:如何在确切位置停止无限动画?

时间:2019-07-09 14:10:02

标签: qt qml

我正在尝试从位置已知的函数中停止无限动画。 我需要动画来制作动画,直到x = pos,然后停止。

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

我试图以这种方式停止它,但这没有帮助。

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

1 个答案:

答案 0 :(得分:1)

如果未达到位置,则可以将表达式设置为属性running的值为true,否则为false。

x属性还与信号onXChanged关联,该信号每次移动项目都会触发。如果您不想/不能更改动画定义,也可以使用它:

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)
    }
}

在上面的代码中,当矩形到达由属性bound定义的X坐标时,动画将停止。

由于该值将是一个浮点数,因此我们不能使用等号,而必须使用边距错误(在我的代码中为1)。