Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 765
Pietro Avatar asked Oct 31 '13 19:10

Pietro


People also ask

How do I keep the same ratio as resizing?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.

How do you scale a QPixmap?

You can scale the pixmap by keeping its aspect ratio every time it changes: QPixmap p; // load pixmap // get label dimensions int w = label->width(); int h = label->height(); // set a scaled pixmap to a w x h window keeping its aspect ratio label->setPixmap(p. scaled(w,h,Qt::KeepAspectRatio));


1 Answers

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.

like image 181
Guilherme Bernal Avatar answered Oct 15 '22 00:10

Guilherme Bernal