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).

I wrote a little program, “Xformer,” in PyQt that demonstrates the relationship between an object’s QTransform matrix and its corresponding transformation, rotation, scale, and shear values.

Download Xformer and try it out. It requires a working copy of PyQt4.

2D Transforms and QGraphicsScene
Tagged on:                     

Leave a Reply