'Preserve aspect ratio during minimize/maximize when displaying image?
I'm trying to implement a scalable image widget with qt creator that will preserve the aspect ratio of the image. All the examples or posts I've found suggest extending QLabel and reimplementing resizeEvent. This is what I've done and it almost works, but for a few problems.
When the main window first opens the images grow slightly and expand the size of the main window (this is not too big a problem).
When I maximize the window all the images scale up, but when I unmaximize the window the images fail to scale back down.
I have tried changing the resizeEvents of both the QLabel subclass (called ClickableImage) and the parent widget that holds the layout containing the ClickableImage. Here is some of the relevant code.
void ClickableImage::resizeEvent(QResizeEvent *e)
{
qDebug() << "Resizing : " << ticker;
ticker++;
int w = e->size().width();
int h = e->size().height();
qDebug() << "W : " << w;
qDebug() << "H : " << h;
image = QPixmap(fname);
image = image.scaled(w-7, h-7, Qt::KeepAspectRatio);
setPixmap(image);
}
Also, I've read the following sources,
Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio
https://docs.huihoo.com/qt/4.2/desktop-screenshot.html
Thanks.
Solution 1:[1]
I have four things that you should try. If you put a larger code example, I would maybe try it for you, but here is what I have for you:
You probably need to call
adjustSize()at the end of the resize event. You probably don't need anupdate()call, but you could try putting one in there and see if it makes a difference.The minimize event should be the same as a
hideEvent(), so put some of your image scaling in there too, if you want it to change the image size on the minimize.The documentation on the Window and Dialog Widgets may help with some of the sizing, but it may also be part of the recursive nature of setting the size of the something in the widget when it gets resized.
An alternative to all this is to let the widget figure out the resizing for you. QLabel has an option to have it scale its contents based on the size it is allowed to take up, so if you create a QLabel, set its pixmap and set the scale contents property, then it will do the fast scaling for you automatically on the resize. You probably would still need to scale it down for the minimize.
Hope that helps. Let me know if you are still having issues.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
