如何在qml中为多个对象设置动画

时间:2016-05-17 20:38:53

标签: javascript jquery animation qml

我试图使用顺序动画一次动画几个对象。为了我的目的,我需要从连续动画(和数字动画)decleration的外部访问它。这样可以正常工作,但在设置时只能动画一个对象。如果我为每个对象定义一个数字动画,这将有效 - 但我不想这样做,因为后来我想在一个循环中分配动画,这个动画的大小会有所不同。所以我故意调用相同数字的动画对象。有没有办法动画一堆对象而不为它定义每个数字动画?这是一些代码:

   Component.onCompleted: {

   seq.access.target = rec1
   seq.access.property = "y"
   seq.access.to = 50
   seq.start()


   seq.access.target = rec2
   seq.access.property = "y"
   seq.access.to = 50
   seq.start()

}

Rectangle{
    id: rec1
    width: 50
    height: 50
    color: "red"
}
Rectangle{
    id: rec2
    x: 100
    width: 50
    height: 50
    color: "blue"
}

SequentialAnimation{
    id: seq
    property alias access: num
    NumberAnimation{id: num}
}

更新你好,谢谢你的回复。 GrecKo的解决方案解决了上述问题,但我还没有...我需要能够在循环中设置每个目标或目标。我认为通过使上面的代码工作,它应该/将在数组中的相同目标时起作用:

...
property int i
Component.onCompleted: {

    var array = [rec1, rec2]

    for(i = 0; i < array.length; i++){

        seq.access.targets = [array[i]]
        seq.access.property = "y"
        seq.access.to = 50
        seq.start()

    }


}

Rectangle{
    id: rec1
    width: 50
    height: 50
    color: "red"
}

Rectangle{
    id: rec2
    x: 100
    width: 50
    height: 50
    color: "blue"
}
SequentialAnimation{
    id: seq
    property alias access: num
    NumberAnimation{id: num}

}

但它不起作用。这就是我需要做的。感谢

2 个答案:

答案 0 :(得分:2)

如果要在多个对象上应用相同的动画,可以使用targets property为动画指定多个目标。

在您的示例中,您可以像这样使用它:

Component.onCompleted: {
    seq.access.targets = [rec1, rec2]
    seq.access.property = "y"
    seq.access.to = 50
    seq.start()
}

答案 1 :(得分:0)

请查看此代码。也许这就是你要找的东西。将其复制到 main.qml

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    visible: true
    width: 1066
    height: 600

    property double time: 0

    Rectangle {
        width: 100
        height: 100
        x: 20
        y: 50 + time * 250
        color: "red"
    }
    Rectangle {
        width: 100
        height: 100
        x: 220
        y: 150
        rotation: time * 360
        color: "blue"
    }
    Rectangle {
        width: 100
        height: 100
        x: 420
        y: 50 + Math.pow(time, 1/3) * 250
        color: "green"
    }
    Rectangle {
        width: 100
        height: 100
        x: 620
        y: 150
        scale: 1 + Math.pow(time, 3)
        color: "lightblue"
    }



    NumberAnimation on time {
        running: true
        loops: Animation.Infinite
        from: 0
        to: 1
        duration: 1000
    }
}

您提供的示例中可能有用的是:

Component.onCompleted: {

   seq.access.target = rec1
   seq.access.property = "y"
   seq.access.to = 50
   seq.start()

}

Rectangle{
    id: rec1
    width: 50
    height: 50
    color: "red"
}
Rectangle{
    id: rec2
    x: 100
    y: rec1.y
    width: 50
    height: 50
    color: "blue"
}

SequentialAnimation{
    id: seq
    property alias access: num
    NumberAnimation{id: num}
}