I am writing a simple graphics editor in Qt C ++. I place QGraphicsItem objects on a QGraphicsScene graphic scene. You must implement the rotation of these objects inside the scene when you click on the corresponding action in the menu. The problem is that you use the void QGraphicsItem :: rotate (qreal angle) function, as it allows you to rotate the object only around the point (0,0) of the graphic scene. I want the object to rotate around its center. I try to do this with setTransform, however, in this case, the rotation is performed once, and when I press the button again, the rotation does not occur.

Please tell me how to fix it. I attach the code of the function called from the slot.

bool PaintScene::rotateObject() { foreach (QGraphicsItem *item, selectedItems()){ QPointF point1; QPointF point2; point1 = item->mapFromScene(item->boundingRect().topLeft()); point2 = item->mapFromScene(item->boundingRect().bottomRight()); x_mid = point2.x() - ((point2.x()-point1.x())/2); y_mid = point2.y() - ((point2.y()-point1.y())/2); item->setTransform(QTransform().translate(x_mid, y_mid).rotate(30).translate(-x_mid, -y_mid)); item->rotate(30); } return true; } 

    2 answers 2

    Ideally, you need to build each object in the coordinate system in which the center of rotation is at (0,0) (that is, you need to remember the initial parameters of the geometry), and with each drawing, first change the scale (if necessary), then rotate, and only after that move. If you need to rotate relative to the current angle of inclination, you can move to (0,0), then rotate, then move back (or get the current transformation matrix, rotate it, then apply to the object)

    Specifically, in Qt, you can try to do it via setTransformOriginPoint (as I understand it, it allows you to apply transformations relative to a given point, that is, it sets where the object moves after rotation). Alternatively, you can reset the transformation matrix with the resetTransform, then rotate with the rotate, then move with the moveBy. For a start, I advise you to try setTransformOriginPoint. Do not forget that the initial coordinates are specified in the object’s own coordinate system (relative to the point of rotation).

      As planned, each QGraphicsItem should have its own coordinate system, and the setRotation () function should work as you wish.