2015-03-03 120 views
0

我試圖瞭解行爲的功能,方法是在屬性發生更改時動畫一個小的Rectangle。 請看下面的例子:使用數字動畫和行爲進行動畫製作

import QtQuick 2.4 
import QtQuick.Controls 1.2 

Item { 
    width: 600 
    height: 80 

    Rectangle { 
     id: rect 
     color: "red" 
     width: 20 
     height: 20 

     property int xval: 0 

     Behavior on xval { 
      NumberAnimation { 
       target: rect 
       property: "x" 
       to: rect.xval 
       duration: 2000 
       easing.type: Easing.InOutQuad 
      } 
     } 
    } 

    Button { 
     anchors.bottom: parent.bottom 
     onClicked: { rect.xval=250 } 
    } 
} 

在這裏,我想對動畫按鈕單擊該項目RECTX財產。但它不具有生命力。現在,如果你更換

to: rect.xval 

to: 400 

的矩形的動畫按鈕單擊預期。我想要做的就是使用用戶設置的值爲Rectangle設置動畫。我錯過了什麼嗎?

回答

2

您不需要額外的屬性來動畫屬性。 Behavior on foo只要改變其值並使其成爲內部動畫的隱含屬性,就會爲foo生成動畫。 您的代碼可以簡單地爲

Item { 
    width: 600 
    height: 80 

    Rectangle { 
     id: rect 
     color: "red" 
     width: 20 
     height: 20 

     Behavior on x { 
      NumberAnimation { 
       duration: 2000 
       easing.type: Easing.InOutQuad 
      } 
     } 
    } 

    Button { 
     anchors.bottom: parent.bottom 
     onClicked: { rect.x=250 } 
    } 
} 
+0

似乎我感到困惑。謝謝你的回答:) – astre 2015-03-04 05:13:24