QGraphicsScene and QGraphicsItems use the QTransform class to move, scale, shear, and rotate objects in the view. For the most part, this works great. Things get a little tricky when you want to keep track of an item’s rotation in terms of a simple angular value. QGraphicsItem doesn’t have a method to get the “rotation,” and neither does QTransform. Instead we have to recover it from the transformation matrix.
The QTransform docs tell us that a rotation is measured in the clockwise direction. Rotation by an angle ? is computed for a given point using the matrix:
How to recover the angular rotation from this matrix? One way is to apply the same matrix to a point at x=0, y=1 and use some simple trig to figure out the angle between its original and new positions.
Enter the excellent atan2 function. Written in python, the math looks like this:
rotation = 180./math.pi * math.atan2(-xform.m21(), xform.m11())
Where xform is our QTransform object (the transformation matrix).
Download Xformer and try it out. It requires a working copy of PyQt4.