qt - 在不使用状态的情况下多次播放 QML 动画

标签 qt animation qml

我试图在每次单击时启动 QML 动画,而不使用状态。第一次单击时会启动,但第二次单击时不会启动。 有理由吗?这是我正在使用的代码。

Image {
    id: head;
    source: "vlad.png";
    height: 80;
    width: 90;
    MouseArea {
        anchors.fill: parent
        onClicked: animateHead.start();
        ParallelAnimation {
            id: animateHead;
            NumberAnimation {
                property int randomValueX: 0;
                function randomize(randomValueX) {
                    randomValueX = (Math.floor(Math.random()*210));
                    return randomValueX;
                }
                target: head;
                properties: "x";
                to: randomize(randomValueX);
                duration: 1000;
                easing {
                    type: Easing.OutBack;
                    overshoot: 5
                }
            }
            NumberAnimation {
                property int randomValueY: 0;
                function randomize(randomValueY) {
                    randomValueY = (Math.floor(Math.random()*210));
                    return randomValueY;
                }
                target: head;
                properties: "y";
                to: randomize(randomValueY);
                duration: 700;
                easing {
                    type: Easing.OutBack;
                    overshoot: 5
                }
            }
        }
    }
}

最佳答案

问题是两个 NumberAnimation 实例的 to 属性的值在 QML 组件初始化期间仅绑定(bind)一次。当您调用 animateHead.start() 时,不会重新计算它们,并且仅当 to 属性的值与动画属性的实际值不同时才会执行动画。这就是为什么它只在第一次起作用。

一个可行的解决方案是:

import QtQuick 1.0

Image {
    id: head;
    source: "vlad.png";
    height: 80;
    width: 90;
    MouseArea {
        anchors.fill: parent
        onClicked: {
            xAnimation.to = Math.floor(Math.random()*210)
            yAnimation.to = Math.floor(Math.random()*210)
            animateHead.start();
        }
        ParallelAnimation {
            id: animateHead;
            NumberAnimation {
                id: xAnimation
                target: head;
                properties: "x";
                duration: 1000;
                easing {
                    type: Easing.OutBack;
                    overshoot: 5
                }
            }
            NumberAnimation {
                id: yAnimation
                target: head;
                properties: "y";
                duration: 1000;
                easing {
                    type: Easing.OutBack;
                    overshoot: 5
                }
            }
        }
    }
}

此处,to 属性的值在 MouseAreaonClicked 处理程序中显式设置。

关于qt - 在不使用状态的情况下多次播放 QML 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017000/

相关文章:

Qt 拖放指示器位置

python - 在 python 中使用 pytest 测试基于 QML 的应用程序

JavaScript Canvas 动画

python - matplotlib生成动画,每个文件都是一个新帧

c++ - 为什么设置 Qt::SplashScreen 标志阻止关闭

qt - 在 SwipeDelegate 上禁用滑动多个项目

python - 计算 float 的小数位

c++ - QQuickView 窗口在鼠标调整大小时卡住

javascript - 无法为 matter.js 设置动画

qt - QML WebEngine查看弹幕内容