Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Animation target

Tags:

qt

qml

qtquick2

Can't switch animation from one object to another. The id changes (it prints 'world' in log), but it doesn't transfer the animation: hello still flashing and world is static.

It works correctly only when calling a.restart(). When there are no functions, just bindings, you can use onChanged and control how the animation stops (complete or pause) 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"
    }
}
like image 686
Velkan Avatar asked Aug 20 '15 06:08

Velkan


2 Answers

You should stop the animation before changing the target:

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

It works fine for me

like image 161
folibis Avatar answered Oct 28 '22 10:10

folibis


I'll use this for now (just added 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"
    }
}

And with binding (animation is switched to another label when pressed):

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"
    }
}
like image 1
Velkan Avatar answered Oct 28 '22 10:10

Velkan