Qml 使用数字和行为设置动画

Qml 使用数字和行为设置动画,qml,Qml,我试图通过在一个小矩形的属性发生变化时设置其动画来理解行为的功能。 考虑下面的例子: 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

我试图通过在一个小矩形的属性发生变化时设置其动画来理解行为的功能。 考虑下面的例子:

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


单击按钮时,矩形将按预期设置动画。我想做的就是使用用户设置的值设置矩形的动画。我遗漏了什么吗?

您不需要额外的属性来设置属性的动画。 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 }
    }
}

好像我搞糊涂了。谢谢你的回答:)
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 }
    }
}