Qt: How do I resize an image and maintain its proportions?

Pietro picture Pietro · Oct 31, 2013 · Viewed 32.5k times · Source

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.

Answer

Guilherme Bernal picture Guilherme Bernal · Oct 31, 2013

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.