If you have a QImage wrapped inside a QLabel, is it possible to scale it up or down when you resize the window and maintain the aspect ratio (so the image doesn't become distorted)? I figured out that it can scale using setScaledContents(), and you can set a minimum and maximum size, but the image still loses its aspect.
It would be great if this could be explained using Python (since I don't know c++), but I'll take what I can get. :-)
Thanks in advance!
I'm showing this as C++, which is what the documentation I'm looking at is in. It shouldn't be too difficult to convert to python.
You need to create a custom derivative of
QLayoutItem
, which overridesbool hasHeightForWidth()
andint heightForWidth( int width)
to preserve the aspect ratio somehow. You could either pass the image in and query it, or you could just set the ratio directly. You'll also need to make sure thewidget()
function returns a pointer to the proper label.Once that is done, you can add a layout item to a layout in the same manner you would a widget. So when your label gets added, change it to use your custom layout item class.
I haven't actually tested any of this, so it is a theoretical solution at this point. I don't know of any way to do this solution through designer, if that was desired.
Convert the image to a
QPixmap
(useQPixmap.fromImage(img)
) and then, you can usescaledToHeight()
.