开发者

How to allow scaling with uniform aspect ratio in (Py)Qt?

开发者 https://www.devze.com 2022-12-09 19:02 出处:网络
If you have a QImage wrapped inside a QLabel,开发者_StackOverflow中文版 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 dis

If you have a QImage wrapped inside a QLabel,开发者_StackOverflow中文版 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 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消