2011-11-04 64 views
2

我试图让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 
       } 
      } 
     } 
    } 
} 

回答

3

的问题是,在两个NumberAnimation实例的to属性的值的QML组件的初始化期间结合只有一次。当您拨打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属性的值在onClicked处理程序MouseArea的明确设置。

0

就像一个笔记,因为我试图解决类似的问题,谷歌搜索这个问题,并决定必须有另一种方式处理动画属性初始化。在Qt 5中,您可以使用PropertyAction立即初始化一些属性。

来自实例PropertyAction类型的文档:

SequentialAnimation { 
    PropertyAction { target: img; property: "opacity"; value: .5 } 
    NumberAnimation { target: img; property: "width"; to: 300; duration: 1000 } 
    PropertyAction { target: img; property: "opacity"; value: 1 } 
} 

我不知道它将如何与ParallelAnimation互动,但它的工作原理非常好SequentialAnimation