qtqgraphicsitemqgraphicspixmapitem

QGraphicsItem : emulating an item origin which is not the top left corner


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 ?


Solution

  • You're overthinking it. QGraphicsPixmapItem already has this functionality built in. See the setOffset method.

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