I want to create a button that can be dragged around by the user, and when released will return to its original position.
During the movement the button must be animated following some easing curve.
What I have until now is this:
import QtQuick 2.2
import QtGraphicalEffects 1.0
Item {
property bool wasDragged: false
property real basePosX: (menuButton.width / 2) - (menuButtonIcon.width / 2) //menuButton.horizontalCenter
property real basePosY: (menuButton.height / 2) - (menuButtonIcon.height / 2) //menuButton.verticalCenter
id: menuButton
x: parent.width - 55
y: parent.height - 60
state: "Closed"
Rectangle {
id: menuButtonIcon
x: basePosX
y: basePosY
color: "#D23F31"
width: 65;
height: 65;
radius: width * 0.5
antialiasing: true
smooth: true
}
Rectangle {
id: menuButtonIconBar1
anchors.centerIn: menuButtonIcon
width: 17
height: 3
antialiasing: true
}
Rectangle {
id: menuButtonIconBar2
anchors.centerIn: menuButtonIcon
width: 17
height: 3
antialiasing: true
rotation: 90
}
MouseArea {
id: mouseArea
anchors.fill: menuButtonIcon
onPressed: menuButton.state = menuButton.state === "Open" ? "Closed" : "Open"
onReleased: {
if (wasDragged) {
wasDragged = false
menuButton.state = "Closed"
}
}
onPositionChanged:
{
wasDragged = true
var currentPosition = mapToItem(parent, mouse.x, mouse.y)
updateButtonPosition(currentPosition.x, currentPosition.y)
}
}
function updateButtonPosition(mouseX, mouseY)
{
console.log("pos change")
menuButtonIcon.x = mouseX - (menuButtonIcon.width / 2);
menuButtonIcon.y = mouseY - (menuButtonIcon.height / 2);
}
states: [
State {
name: "Closed"
PropertyChanges { target: menuButtonIcon; x: basePosX; y: basePosY}
},
State {
name: "Open"
PropertyChanges { target: menuButtonIconBar1; rotation: 135;}
PropertyChanges { target: menuButtonIconBar2; rotation: 225;}
PropertyChanges { target: menuButtonIcon; x: basePosX; y: basePosY}
}
]
transitions: [
Transition {
SpringAnimation { target: menuButtonIcon; properties: "x, y"; spring: 3; damping: 0.25; epsilon: 0.2; mass: 1; modulus: 0; velocity: 0 }
SpringAnimation { target: menuButtonIconBar1; properties: "rotation, scale"; spring: 3; damping: 0.25; epsilon: 0.5; mass: 1; modulus: 0; velocity: 0 }
SpringAnimation { target: menuButtonIconBar2; properties: "rotation, scale"; spring: 3; damping: 0.25; epsilon: 0.5; mass: 1; modulus: 0; velocity: 0 }
}
]
}
But the issue with this is that if you drag it and hold still before the rotation animation ends, the button will return to its original position, even though you never released it.
If you remove the two Rectangle
s forming the cross, as well as their animations, then it works as intended.
Why is the button returning to its original positions by itself, and how can that be fixed?