Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 903
Jérôme Avatar asked May 25 '09 14:05

Jérôme


2 Answers

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.

like image 140
Parker Coates Avatar answered Nov 15 '22 08:11

Parker Coates


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));
like image 44
Georg Schölly Avatar answered Nov 15 '22 08:11

Georg Schölly