pra7
pra7

Reputation: 884

How to add animation to a component while destroying in QML

I am adding Animation to my project and most of the UI is dynamic. Currently, i am not able to add animation to the Component while destroying. Following is the test application code which describes the same:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    property bool removeClicked : true

    Row{
        anchors.bottom: parent.bottom
        spacing:20
        Button{
            text:"Add"

            onClicked: {
                removeClicked = false
                comp.createObject(myrow)
            }
        }

        Button{
            id:remBtn
            text:"Remove"

            onClicked: {
                removeClicked = true
                myrow.children[0].destroy() //Destroy the object

            }
        }
    }

    Row{
        id:myrow
        height:40
        spacing:20
    }

    Component{
        id:comp
        Rectangle{
            width:20
            height:30
            color: "red"

            NumberAnimation on opacity{
                id: destroyAnimation
                from :removeClicked ? 1:0
                to: removeClicked ? 0:1
                duration: 1000
            }
        }
    }
}

Any help will be Appreciated!!!

Upvotes: 1

Views: 1358

Answers (1)

Shou should perform the animation before calling destroy on your dynamically created items. You could use a SequentialAnimation, combined with a ScriptAction to do so.

Here's a small example (the dynamic balls get destroyed when one clicks on them).

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

Window {
    visible: true
    width: 640
    height: 480

    Button{
        text:"Add"
        anchors.centerIn: parent
        onClicked: {
            comp.createObject(parent)
        }
    }

    Component{
        id:comp
        Rectangle{
            id: ball
            height:30
            width:height
            radius: height/2
            x: Math.random()*parent.width-width
            y: Math.random()*parent.height-height
            color: Qt.hsla(Math.random(), 0.5, 0.5, 1)
            opacity: 0

            Component.onCompleted: opacity = 1

            Behavior on opacity{ NumberAnimation {}}
            SequentialAnimation
            {
                id: destroyAnim
                ScriptAction{script: ball.opacity = 0}
                NumberAnimation{target: ball; property:"scale"; to: 5}
                ScriptAction{script: ball.destroy()}
            }

            MouseArea
            {
                anchors.fill: parent
                onClicked:destroyAnim.start()
            }
        }
    }
}

Upvotes: 1

Related Questions