tags:

views:

397

answers:

2

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!

A: 

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

Aaron Digulla
Thanks Aaron! That doesn't do quite what I'm looking for. That statically scales the image (QPixmap) upon creation, but it doesn't scale when I resize the window. Any other ideas?
jgoney
In that case, don't scale but put a QLabel into the window and call `setPixmap()` on it. Qt will then scale the image along with the label and it *should* preserve the aspect.
Aaron Digulla
Hi! Thanks again. Setting a QPixmap didn't scale, but it is good to know that I can set it with a Pixmap directly rather than setting a QImage first.
jgoney
+2  A: 

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.

Caleb Huitt - cjhuitt
Hi thanks! This looks like it'll probably work, but I think I might just let it slide for the time being. I think it's beyond the scope of my Qt capabilities and my deadline is coming up sooner than I'd prefer. I'll try to revisit this after I get closer to finishing and get back with you!
jgoney