How to Rotate a Rectangle using a handle? - And Around we go, maybe ? My Handle is broken
-
Hi all.
I am trying to create a handle that will rotate a rectangle like this.......
https://www.eatoncode.com/resources/shareit/Desktop_2019-03-20_21.06.19.mp4
I am using the code from Stack Over Flow
https://stackoverflow.com/questions/17275531/how-to-rotate-a-qml-rectangle-by-dragging
I am trying to adapt it so I can create a handle on a simple Rectangle.
import QtQuick 2.12 import QtQuick.Controls 2.5 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Rotate Handle") Item { id: rootbox width: 200 height: 200 x: 200 y:150 property real centerX : (width / 2); property real centerY : (height / 2); Rectangle { id: rect color: "red" anchors.fill: parent Rectangle { id: line color: "blue" width: 3 height:35 x: (parent.width / 2) -6 y: 0 anchors { top: parent.top topMargin: parent.width horizontalCenter: parent.horizontalCenter; } } //Center Rotate Rectangle { id: handle; width: 20 height: 20 radius: 20 x: (parent.width / 2) -6 y: 0 anchors { top: parent.top topMargin: parent.width + 20 horizontalCenter: parent.horizontalCenter; } color: "blue" antialiasing: true; transformOrigin: Item.Bottom MouseArea{ anchors.fill: parent; onPositionChanged: { var point = mapToItem (rootbox, mouse.x, mouse.y); var diffX = (point.x - rootbox.centerX); var diffY = -1 * (point.y - rootbox.centerY); var rad = Math.atan (diffY / diffX); var deg = (rad * 180 / Math.PI); if (diffX > 0 && diffY > 0) { rect.rotation = 90 - Math.abs (deg); } else if (diffX > 0 && diffY < 0) { rect.rotation = 90 + Math.abs (deg); } else if (diffX < 0 && diffY > 0) { rect.rotation = 270 + Math.abs (deg); } else if (diffX < 0 && diffY < 0) { rect.rotation = 270 - Math.abs (deg); } } } } } } }
I am using QT 5.12.2 but I am sure it will work with anything version above 5.9, Just create new QML project and paste the code into main.qml and run
I can't seem to get the handle to work correctly... I think it's an anchor issue but if I change the anchor, I can't get it spin all the way around without some effort.
Here is what I have so far...
https://www.eatoncode.com/resources/shareit/Desktop_2019-03-20_21.13.00.mp4
Does anyone have any ideas to improve this?
Thanks in advance.
-
hi @EatonCode
add - everywhere
onPositionChanged: { ... if (diffX > 0 && diffY > 0) { rect.rotation = -90 - Math.abs (deg); } else if (diffX > 0 && diffY < 0) { rect.rotation = -90 + Math.abs (deg); } else if (diffX < 0 && diffY > 0) { rect.rotation = -270 + Math.abs (deg); } else if (diffX < 0 && diffY < 0) { rect.rotation = -270 - Math.abs (deg); } }
-
@LeLev said in How to Rotate a Rectangle using a handle? - And Around we go, maybe ? My Handle is broken:
everywhere
Please forgive me but I don't understand your answer. Do you mean to add the onPositionChanged in every MouseArea in Every Rectangle?