Search code examples
qtqmlqt-quick

How to write a number animation on the mouse button press event in QML?


import QtQuick 1.0

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

   MouseArea 
   {
    anchors.fill: parent

    onPressed:
    {
      NumberAnimation 
      { 
        target: parent.x
        to: 50; 
        duration: 1000 
      }
    }
  }
}

I expect this code to shift the x position of the rectangle on the button press event, but this does nothing.

Where am I going wrong?


Solution

  • You are defining an NumberAnimation in a signal handler, it's not going to work properly. Furthermore, NumberAnimation target should be an item, and here you are targeting a property of an item. Here is your code corrected :

    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 
        }
      }
    }
    

    If your rectangle animation should revert when mouse is released, you would like to take benefit of a proper state definition, and animate property "x" at each state change (between default and "pressed" states. Here is a self contained example :

    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 } 
        }
      }
    }
    

    If you need more complex animation, define a proper Transition. A simple Behavior, here, is more readable I find.