It might be a little late, but maybe someone else will find this information useful in the future. I am pretty new to Qt, so please correct me if my explanations are not correct. I believe that the problem lies in the changing of the origin point itself. Because your two anchor points exist relative to the coordinates of your MyView item, they will also change their position every time you change the origin point. This is probably the reason why you get this weird jumping behavior. Another way of implementing the desired behavior would be to translate the whole MyView item. So you could implement the following modifications to your existing code. First, change the mousePressEvent method so that you no longer change the origin.
MyView::mousePressEvent
void MyView::mousePressEvent(QGraphicsSceneMouseEvent *event) {
_tapPoint = event->pos();
auto cp1 = _anchor1.center(); // get center point of anchor 1
auto cp2 = _anchor2.center(); // get center point of anchor 2
// Anchor 1 clicked
if (_anchor1.contains(_tapPoint)) {
_viewState = ANCHOR1;
}
// anchor 2 clicked
else if (_anchor2.contains(_tapPoint)) {
_viewState = ANCHOR2;
}
// View clicked
else {
QGraphicsItem::mousePressEvent(event);
_viewState = VIEW;
}
}
Secondly, use a transformation matrix to rotate the whole item.
MyView::mouseMoveEvent
void MyView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
auto p = event->pos();
auto cp1 = _anchor1.center(); // get center point of anchor 1
auto cp2 = _anchor2.center(); // get center point of anchor 2
QTransform transformMatrix;
switch (_viewState) {
case ANCHOR1: {
// calculate the angle of the rotation based on the mouse touch
auto angle = qRadiansToDegrees(qAtan2(p.y() - _anchor2.y(), _width));
transformMatrix.translate(cp2.x(), cp2.y());
transformMatrix.rotate(-angle);
transformMatrix.translate(-cp2.x(), -cp2.y());
setTransform(transformMatrix, true);
break;
}
case ANCHOR2: {
// calculate the angle of the rotation based on the mouse touch
auto angle = qRadiansToDegrees(qAtan2(p.y() - _anchor1.y(), _width));
transformMatrix.translate(cp1.x(), cp1.y());
transformMatrix.rotate(angle);
transformMatrix.translate(-cp1.x(), -cp1.y());
setTransform(transformMatrix, true);
break;
}
default:
QGraphicsItem::mouseMoveEvent(event); // move the item normally
}
}
In this solution, I just change the rotation origin manually by first translating the whole item by the coordinates of the center point of the selected anchor.