如何在QML中使用鼠标按键事件编写数字动画?

Aqu*_*irl 1 qt qml qt-quick

import QtQuick 1.0

Rectangle 
{
  width: 100; height: 100
  color: "red"

   MouseArea 
   {
    anchors.fill: parent

    onPressed:
    {
      NumberAnimation 
      { 
        target: parent.x
        to: 50; 
        duration: 1000 
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望这段代码能够x在按钮按下事件中移动矩形的位置,但这没有任何作用.

我哪里错了?

eps*_*lon 5

您正在信号处理程序中定义NumberAnimation,它无法正常工作.此外,NumberAnimation目标应该是一个项目,在这里您要定位项目的属性.这是你的代码更正:

import QtQuick 1.0

Rectangle 
{
  id: rect
  width: 100; height: 100
  color: "red"

   MouseArea 
   {
    anchors.fill: parent

    onPressed:
    {
        animation.start()
    }

    NumberAnimation 
    { 
        id: animation
        target: rect
        property: "x"
        to: 50; 
        duration: 1000 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果在释放鼠标时你的矩形动画应该还原,你可以利用正确的状态定义,并在每个状态更改(默认和"按下"状态之间)动画属性"x".这是一个自包含的示例:

import QtQuick 1.0

Rectangle {
  id: root
  width: 360
  height: 200

  Rectangle 
  {
    id: rect
    width: 100; height: 100
    color: "red"

    MouseArea 
    {
      id: mouse
      anchors.fill: parent
    }

    states: [
      State {
        name: "pressed"
        when: mouse.pressed

        PropertyChanges {
          target: rect
          x: 50
        }
      }
    ]

    Behavior on x {
      NumberAnimation { duration: 1000 } 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要更复杂的动画,请定义合适的动画Transition.Behavior这里简单,我发现更具可读性.