Rotate QGraphicsPixmapItem results in shear if resizing without keeping aspect ratio
Asked Answered
C

1

1

I am trying to rotate a QGraphicsPixmapItem child. For other QGraphicsItem, rotation and scaling work fine. But for a QGraphicsPixmapItem, if the size does not keep aspect ratio, instead of rotation I get shear.

sample code:

#include <QApplication>
#include <QGraphicsView>
#include <QMessageBox>
#include <QGraphicsPixmapItem>
#include <QFileDialog>

int main(int argc, char *argv[])
{
    QGraphicsScene s;
    s.setSceneRect(-200, -200, 500, 500);
    QGraphicsView view(&s);
    view.show();

    QGraphicsPixmapItem p;
    QString fileName = QFileDialog::getOpenFileName(0, QObject::tr("Open Image File"), QString(), QObject::tr("Png files (*.png);;Jpeg files (*.jpg *.jpeg);;Bitmap files (*.bmp)"));
    p.setPixmap(QPixmap(fileName));
    s.addItem(&p);
    QMessageBox::information(0, "", "");

    QTransform original = p.transform();

    // scale aspect ratio then rotate
    QTransform scalingTransform0(0.5, 0, 0, 0, 0.5, 0, 0, 0, 1);
    // p.setTransformOriginPoint(p.boundingRect().center()); // doesn't help shear
    p.setTransform(scalingTransform0 * original);
    p.setRotation(20);
    QMessageBox::information(0, "", "");

    // scale
    QTransform scalingTransform(0.5, 0, 0, 0, 1, 0, 0, 0, 1);
    p.setTransform(scalingTransform * original);
    QMessageBox::information(0, "", "");

    // rotate
    p.setRotation(20);
    QMessageBox::information(0, "", "");

    // unrotate then rotate again
    p.setRotation(0);
    QMessageBox::information(0, "", "");
    QTransform rotTransform = p.transform().rotate(20);
    p.setTransform(rotTransform);

    // or p.rotate(20);
    return app.exec();
}

Result:

enter image description here

I don't know how to get simple rotation, without shearing, for QGraphicsPixmapItems, and the item must remember the rotation.

Consentient answered 5/8, 2015 at 22:53 Comment(2)
possible duplicate of Resizing and rotating a QGraphicsItem results in odd shapeMontymonument
It is duplicate - after weeks of struggling with this problem, a different approach found an answer :-) Which is why I had linked the questions.Consentient
C
0

It is still a mystery why QGraphicsPixmapItem behaves so inconsistently.

A solution:
When scaling the item, scale the pixmap, apply resulting pixmap to item.
In that case rotation will work (because QGraphicsPixmapItem is not really scaled).

QPixmap p1 = pixmap.scaled(100, 100, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
p.setPixmap(p1);
p.setRotation(20);

This approach loses quality, so I ended up reloading the file

QPixmap p1 = (QPixmap(fileName)).scaled(100, 100, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
p.setPixmap(p1);
p.setRotation(20);

If there is a better solution, I will be happy to see it.

Consentient answered 6/8, 2015 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.