QGraphicsItem: emulating the source of an item that is not the top left corner

My application is using Qt.

I have a class that inherits from QGraphicsPixmapItem.

When you apply transformations to these elements (such as rotations), the origin of the element (or pivot point) is always in the upper left corner.

I would like to change this origin so that, for example, when adjusting the position of an element, this will actually change the center of the pixmap.

Or, if I apply rotation, the origin of rotation will be the center of the pixelmap.

I didn't find a way to do this right out of the box with Qt, so I decided to override 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 it would work as the Qt doc mentions that the position of an element and its transformation matrix are two different concepts.

But it doesn't work.

Any idea?

+3


a source to share


3 answers


You think too much about it. QGraphicsPixmapItem is already built into this functionality. See The setOffset Method .



So, to set the original position of an element to its center, just do setOffset( -0.5 * QPointF( width(), height() ) );

each time you set the pixmap.

+4


a source


Qt documentation about rotation :



void QGraphicsItem :: rotate (qreal angle)

Rotates the current element clockwise around its origin. Translate arbitrary point (x, y), you need to combine translation and 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));

      

+2


a source


You need to create a rotate function that converts the object to its parent (0, 0) angle, which rotates and moves the object to its original location.

-1


a source







All Articles