Friday, July 23, 2010

Rotation and mirroring QGraphicsItem in Qt

Recently I started to learn Qt Graphics View to convert one of my existing game to use Qt graphics view framework.

During this I learned some new things that I would like to share here.

Rotating QGraphicsItem,

Generally when you rotate QGraphicsItem, it will rotate in reference to item's origin (0,0). To apply rotation in reference to center of item  use following line of code.

graphicsItem->setTransform(QTransform().translate(centerX, centerY).rotate(angle).translate(-centerX, -centerY));

Mirroring or flipping QGraphicsItem,

To mirror item, you can use scale operation on QGraphicsItem. To flip item on y axis you following code,


here 1 scale factor will keep size to its original size and negative value will flip item on axis. Similarly to flip item on x axis use following code.



  1. Hey, there is simpler solution to rotating around center of an item. Check out QGraphicsItem::setTransformOriginPoint(const QPointF &origin). Then you can do something like this graphicsItem->setTransformOriginPoint(graphicsItem->boundingRect().center()); and then graphicsItem->setRotation(angle); will do what you want. Cheers. ;)

  2. I tried using setTransformOriginPoint, but somehow could not get it working then finally decidede to use above code. But thanks, I will try your solution.

  3. I was struggling to get setTransformOriginPoint working until found this way. Sure I did something wrong that it didn't work for me, but I was just tired of it so this way was just in time. Thanks a lot!

  4. :) Thanks for comment. Glad it helped you.

  5. Just the right clue at just the right time. Was getting rotation about a scene central point (think of a photography slide moving orbitally around a projector carousel) rather than local to the QGraphicsItem. Thanks for posting, Kunai. (Never did find Milan's plausible sounding method in the Qt docs, oddly.) - Geo

  6. scale(double,double) is deprecated on Qt 4.7+ (it mess transformation matrices and absolute pos/rotation/scale).
    Frankly, this mess between transformation matrices and "absolute" transformation is disappointing.

  7. Thanks man. setTransformOriginPoint has not seemed to work for me either (perhaps I'm missing a mapToItem or something). But this worked like a charm.