更改动画目标

时间:2015-08-20 06:38:09

标签: qt qml qtquick2

无法将动画从一个对象切换到另一个对象。 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"
    }
}

2 个答案:

答案 0 :(得分:1)

您应该在更改目标之前停止动画:

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

它适用于我

答案 1 :(得分:1)

我现在就使用它(刚刚添加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"
    }
}