1
votes

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!

2

2 Answers

2
votes

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 overrides bool hasHeightForWidth() and int 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 the widget() 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.

0
votes

Convert the image to a QPixmap (use QPixmap.fromImage(img)) and then, you can use scaledToHeight().