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.
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.
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With