tags:

views:

713

answers:

3

My application is using Qt.

I have a class which is inheriting QGraphicsPixmapItem.

When applying transformations on these items (for instance, rotations), the origin of the item (or the pivot point) is always the top left corner.

I'd like to change this origin, so that, for instance, when setting the position of the item, this would put actually change the center of the pixmap.

Or, if I'm applying a rotation, the rotation's origin would be the center of the pixmap.

I haven't found a way to do it straight out of the box with Qt, so I thougth of reimplementing itemChange() like this :

QVariant JGraphicsPixmapItem::itemChange(GraphicsItemChange Change, const QVariant& rValue)
{
    switch (Change)
    {
    case QGraphicsItem::ItemPositionHasChanged:
        // Emulate a pivot point in the center of the image
        this->translate(this->boundingRect().width() / 2,
                        this->boundingRect().height() / 2);
        break;
    case QGraphicsItem::ItemTransformHasChanged:
        break;
    }
    return QGraphicsItem::itemChange(Change, rValue);
}

I thought this would work, as Qt's doc mentions that the position of an item and its transform matrix are two different concepts.

But it is not working.

Any idea ?

+1  A: 

The Qt-documentation about rotating:

void QGraphicsItem::rotate ( qreal angle )

Rotates the current item transformation angle degrees clockwise around its origin. To translate around an arbitrary point (x, y), you need to combine translation and rotation with setTransform().

Example:

// Rotate an item 45 degrees around (0, 0).
item->rotate(45);

// Rotate an item 45 degrees around (x, y).
item->setTransform(QTransform().translate(x, y).rotate(45).translate(-x, -y));
Georg
I actually foudn that in the doc, but I didn't mention in my question that I wanted to use QGraphicsItemAnimation, for which there is no setTransformAt() method, only setPosAt, setRotationAt, etc.
Jérôme
A: 

You need to create a rotate function, that translate the object to the parent's (0, 0) corner do the rotation and move the object to the original location.

xgoan
+2  A: 

You're overthinking it. QGraphicsPixmapItem already has this functionality built in. See the setOffset method. (http://doc.trolltech.com/4.5/qgraphicspixmapitem.html#setOffset)

So to set the item origin at its centre, just do setOffset( -0.5 * QPointF( width(), height() ) ); every time you set the pixmap.

Parker
You are completely right : I didn't see this offset property. It is exactly what I needed. My app is now working as expected. Thanks !
Jérôme