Sam
Sam

Reputation: 133

How to rotate an image around its centre in QT QWidgets C++?

I am trying to rotate am image around its origin(center) in QT using QWidgts in C++. I experimented a lot of things here, but no matter what I do, the image keeps rotating around some arbitrary position I have no clue of. Kindly, help me out here. I am new to QT.

void gaugeWithRedZoneImage::rotate()
{
    QPixmap pixmap(*gaugeMainScreen->pixmap());
    QMatrix rm;
    rm.translate(0, 0);
    rm.rotate(-360);
    pixmap = pixmap.transformed(rm);
    gaugeMainScreen->setPixmap(pixmap);

    /*QTransform rotate_disc;
    rotate_disc.translate(pixmap.width()/2.0 , pixmap.height()/2.0);
    rotate_disc.rotate(-60);
    rotate_disc.translate(-(pixmap.width()/2.0) , -(pixmap.height()/2.0));
    pixmap = pixmap.transformed(rotate_disc);
    gaugeMainScreen->setPixmap(pixmap);*/
}

Upvotes: 4

Views: 2425

Answers (2)

Moreira
Moreira

Reputation: 586

As ypnos said, your problem isn't the rotation center. When you rotate your image, its width and height will most likely change and no longer fit your container (gaugeMainScreen) dimensions.

You have some possibilities to overcome this problem. One of them is to set your container to scale its contents (you can use the method setScaledContents()). In this case, you have to keep the original image around and use it whenever you apply a rotation, otherwise your image will appear increasingly smaller.

Upvotes: 1

ypnos
ypnos

Reputation: 52417

Form the documentation of QPixmap::transformed():

The transformation transform is internally adjusted to compensate for unwanted translation; i.e. the pixmap produced is the smallest pixmap that contains all the transformed points of the original pixmap.

This means that the method ensures no clipping takes place by appending the canvas. No matter what your rotation center was, the automatic extension of canvas will almost always result in a perceived shift.

Image examples might help to further diagnose the problem.

Upvotes: 2

Related Questions