如何在QML中销毁时向组件添加动画

时间:2018-04-13 10:52:05

标签: qt animation qml qtquick2 qtquickcontrols2

我正在为我的项目添加动画,大多数UI都是动态的。目前,我无法在销毁时向Component添加动画。以下是测试应用程序代码,它描述了相同的内容:

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

任何帮助都会得到赞赏!!!

1 个答案:

答案 0 :(得分:1)

Shou应该在动态创建的项目上调用destroy 之前执行动画。您可以使用SequentialAnimation并结合ScriptAction来执行此操作。

这是一个小例子(动态球在点击它们时会被破坏)。

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