2011-11-04 65 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