10

This Qt example shows how to resize an image contained in a dialog, so that when the dialog is resized, the image stretches accordingly.

How can I resize an image in the same way, without distorting it / keeping its proportions the same?

Of course if the width/height ratio of the dialog is different from the one of the image, I will get a "grey" area.
I found the Qt::KeepAspectRatio enum, but not the function to use it with.

Update: This is the code I am trying with:

QImage image(path);
QImage image2 = image.scaled(200, 200, Qt::KeepAspectRatio);
QLabel *plotImg = new QLabel;
plotImg->setScaledContents(true);
plotImg->setPixmap(QPixmap::fromImage(image2));

The image does not maintain a constant aspect ratio when the label is resized. And it looses resolution after the rescaling.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Pietro
  • 12,086
  • 26
  • 100
  • 193

1 Answers1

22

Use the QImage::scaled function.

QImage img("someimage.png");
QImage img2 = img.scaled(100, 100, Qt::KeepAspectRatio);

In case you need it for QPixmap, a function with the same name exists.

Guilherme Bernal
  • 8,183
  • 25
  • 43
  • I updated my question, including your suggestion. – Pietro Nov 01 '13 at 11:58
  • 2
    A `QLabel` will not resize the pixmap it shows unless [`scaledContents`](http://qt-project.org/doc/qt-4.8/qlabel.html#scaledContents-prop) is set. Also, you may want to pass [`Qt::SmoothTransformation`](http://qt-project.org/doc/qt-4.8/qt.html#TransformationMode-enum) as the last parameter to `scaled`. – Guilherme Bernal Nov 01 '13 at 12:39
  • scaledContents was already in my code, I just forgot to copy it in my example. Now I fixed it. The result is still the same. – Pietro Nov 01 '13 at 14:22
  • Qt::SmoothTransformation just determines the quality/algorithm the image is resized with. It has no effect on the width/height ratio. – Pietro Nov 01 '13 at 14:24
  • Just don't use `scaledContents`. You can react to the [`resizeEvent`](http://qt-project.org/doc/qt-4.8/qwidget.html#resizeEvent) of your window to reset the pixmap with a new scaled one. – Guilherme Bernal Nov 01 '13 at 14:31