改变动画目标

Changing Animation target

无法将动画从一个对象切换到另一个对象。 id 发生变化(它在日志中打印 'world'),但它不传输动画:hello 仍在闪烁,world 是静态的。

只有在调用 a.restart() 时才能正常工作。当没有功能,只有绑定时,您可以使用 onChanged 并控制动画停止(完成或暂停)的方式 if (running) { complete(); restart(); }.

import QtQuick 2.5

Column {
    ColorAnimation {
        id: a

        target: lab1
        property: "color"

        running: true
        loops: Animation.Infinite
        duration: 500

        from: "black"
        to: "red"
    }

    Text {
        id: lab1

        text: "hello"

        MouseArea {
            anchors.fill: parent
            onClicked: {
                a.target = lab2
                console.log("changed")
                console.log(a.target.text)
            }
        }
    }

    Text {
        id: lab2

        text: "world"
    }
}

你应该在改变目标之前停止动画:

a.running = false
a.target = lab2
a.running = true

对我来说很好

我暂时使用它(刚刚添加了 onTargetChanged):

import QtQuick 2.5

Column {
    ColorAnimation {
        id: a

        target: lab1

        onTargetChanged: {
            if (running) { complete(); restart(); }
        }

        property: "color"

        running: true
        loops: Animation.Infinite
        duration: 500

        from: "black"
        to: "red"
    }

    Text {
        id: lab1

        text: "hello"

        MouseArea {
            anchors.fill: parent
            onClicked: {
                a.target = lab2
                console.log("changed")
                console.log(a.target.text)
            }
        }
    }

    Text {
        id: lab2

        text: "world"
    }
}

并带有绑定(按下时动画切换到另一个标签):

import QtQuick 2.5

Column {
    id: root

    ColorAnimation {
        id: a

        target: ma.pressed ? lab2 : lab1

        onTargetChanged: {
            if (running) { complete(); restart(); }
        }

        property: "color"

        running: true
        loops: Animation.Infinite
        duration: 500

        from: "black"
        to: "red"
    }

    Text {
        id: lab1

        text: "hello"

        MouseArea {
            id: ma
            anchors.fill: parent
        }
    }

    Text {
        id: lab2

        text: "world"
    }
}