首页 > 解决方案 > Qt NumberAnimation 属性绑定循环问题

问题描述

我是 Qt QML 的新手。我正在使用 JS 动态创建 numberAnimation 但收到绑定循环警告。

qrc:/main.qml:18:9:QML 项目:检测到属性“anime”的绑定循环

import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    id : global
    width: 550
    height: 550
    visible: true
    title: qsTr("Hello World")

    Rectangle{
        id : exp
        x : 0
        y : 0
        color : "red"
        width : 50 ; height : 50

        property var anime : createAnimation(exp);

        function createAnimation(parent){
            let numAnime = Qt.createQmlObject("import QtQuick 2.12; NumberAnimation { onStopped:{to = Math.random()*500; restart() }}", parent)
            numAnime.duration = 500
            numAnime.easing.type = Easing.OutInSine
            numAnime.target = parent
            numAnime.property = "x"
            numAnime.running = true
            return numAnime
        }
    }
}

另外,有没有办法在 createAnimation(args) 函数中定义 onStopped 主体?

标签: qtqml

解决方案


anime您可以通过在 中分配绑定来删除绑定Component.onCompleted。是的,您可以通过将其连接到函数来onStopped在主体中定义,如下所示:createAnimation

    Rectangle{
        id : exp
        x : 0
        y : 0
        color : "red"
        width : 50 ; height : 50

        property var anime
        Component.onCompleted: anime = createAnimation(exp);

        function createAnimation(parent){
            let numAnime = Qt.createQmlObject("import QtQuick 2.12; NumberAnimation {}", parent)
            numAnime.duration = 500
            numAnime.easing.type = Easing.OutInSine
            numAnime.target = parent
            numAnime.property = "x"
            numAnime.running = true
            numAnime.onStopped.connect(function() { numAnime.to = Math.random() * 500; numAnime.restart() })
            return numAnime
        }
    }

推荐阅读