QGraphicsItem and its transformOriginPoint
-
Hi everybody,
I have a derived class of QGraphicsItem, which for the simplicity of this post just draws a line. When the user presses a button, this line should rotate by some amount of degrees. This could be realized with the following function:void SomeItem::rotate(float degrees) { setRotation(rotation() - degrees); }
However, I now would like to rotate around the line's center. Or more generally, around any given point. I have tried the following two solutions so far:
Suggestion 1:
void SomeItem::rotate(float degrees, QPointF const& sceneAnchor) { QPointF localAnchor(mapFromScene(sceneAnchor)); setTransform(QTransform().translate(localAnchor.x(), localAnchor.y()) .rotate(degrees) .translate(-localAnchor.x(), -localAnchor.y())); }
This seems to work nicely at first; however, when I now move the item using the standard drag functionalities (
setFlag(QGraphicsItem::ItemIsMovable, true);
), the item jumps to a different location when I release the mouse button.Suggestion 2:
void SomeItem::rotate(float degrees, QPointF const& sceneAnchor) { setTransformOriginPoint(mapFromScene(sceneAnchor)); setRotation(rotation() - degrees); setTransformOriginPoint(QPointF(0,0)); }
However, as the transformOriginPoint seems to be valid for all transformations, this still results in a rotation around (0,0). Omitting the last line results in the same problem as with suggestion 1, which means that the item jumps when it is moved.
What is the proper way to go here?
Best regards and thank you,
Tim -
If I understood you right all you need is to set setTransformOriginPoint() once ( when you modify or create your item ) to the center of your line.
And this center has to be defined in item (not scene ) coordinates. -
Hi, thank you very much for your reply.
Yes, in theory, I also thought this should be enough. However, when I do so, the item performs these described strange jumps when I move it (i.e. when I release the mouse button after moving it). And of course, I would like to get rid of them as well :) -
@lopatim
Did you ever figure out this problem? I'm running into a similar issue with using the default move functionality (setFlag(QGraphicsItem::ItemIsMovable, true) )and trying to do rotations. There is an odd jump when I switch between move and rotate. When I look at the transform() matrix for the QGraphicsItem in the debugger it is just the identity matrix. Any ideas?