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

How to add animation to a component while destroying in QML

我正在将动画添加到我的项目中,大部分 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
            }
        }
    }
}

我们将不胜感激!!!

Shou 应该在 调用动态创建的项目 destroy 之前执行动画 。您可以使用 SequentialAnimation, combined with a 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()
            }
        }
    }
}