微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

组合多个 QML 行为

如何解决组合多个 QML 行为

我希望在 x 和/或 y 发生变化时平滑地为对象设置动画。我让它工作(如下所示),但我不知道如何组合 x 和 y 行为,所以我创建了 2 个行为。

现在,我想在整个动画完成时(x 和/或 y)发出一个信号。我可以创建 2 个标志并测试它们在发出完成信号时是否设置。但是,如果只有一维动画,我将永远等待第二个信号。

有没有简单的解决方案? (否则我必须通过预先检查 x 或 y 是否真的会改变来预设标志)

Behavior on x {
    id: moveSlowlyX
    enabled: true
    NumberAnimation {
        duration: m_time
        easing.type: Easing.InOutQuad
    }
}

Behavior on y {
    id: moveSlowlyY
    enabled: true
    NumberAnimation {
        duration: m_time
        easing.type: Easing.InOutQuad
    }
}

解决方法

您可以使用从 Animation 继承的所有类中存在的标志 running 来完成此操作。使用第三个布尔属性将两个动画的运行状态绑定在一起。这将告诉两者何时停止。这是一个源自您的完整工作示例 - 按钮使 Rectangle 在一个轴或两个轴上移动,并且颜色会在动画时发生变化,并在两个动画完成时记录:

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window {
    id: applicationWindow
    width: 640
    height: 480
    visible: true

    Rectangle {
        id: rect
        color: animationRunning ? "blue" : "red"
        width: 100
        height: 100

        // if either animation is running (or both),this is true
        // false only when neither animation is running
        property bool animationRunning: xAnim.running || yAnim.running

        onAnimationRunningChanged: {
            if (animationRunning === false) {
                console.log("ANIMATION COMPLETE")
            }
        }

        Behavior on x {
            enabled: true
            NumberAnimation {
                id: xAnim
                duration: 500
                easing.type: Easing.InOutQuad
            }
        }

        Behavior on y {
            enabled: true
            NumberAnimation {
                id: yAnim
                duration: 500
                easing.type: Easing.InOutQuad
            }
        }
    }

    Row { // controls for visually testing/verifying logic
        Button {
            text: "move X"
            onClicked: rect.x = Math.random()* parent.width
        }
        Button {
            text: "move Y"
            onClicked: rect.y = Math.random()* parent.height
        }
        Button {
            text: "move Both"
            onClicked: {
                rect.y = Math.random()* parent.height
                rect.x = Math.random()* parent.width
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。