PDA

View Full Version : QLabel to display an image and preserve the aspect ratio



psih128
7th September 2009, 12:18
Hi

This sounds very simple, but I can not figure it out...

I need to display an image on a dialog as a part of the layout and the image should preserve the aspect ratio when the dialog size is changed and the QLabel geometry is changed accordingly. I tried to use QLabel for this, but it does not seem to be able to scale the image proportionally. Is there any other solution?

Thanks
Anton

yogeshgokul
7th September 2009, 12:28
At the time of scaling the image. You can use these options:

Qt::KeepAspectRatio
Qt::KeepAspectRatioByExpanding
Whatever suits your requirement.

psih128
7th September 2009, 14:18
At the time of scaling the image. You can use these options:

Qt::KeepAspectRatio
Qt::KeepAspectRatioByExpanding
Whatever suits your requirement.
So you propose to create a custom widget, re-implement paintEvent and draw a properly scaled image, right?

Is there a way to do that via Designer without writing code - this is what I was thinking about.

yogeshgokul
8th September 2009, 05:25
So you propose to create a custom widget, re-implement paintEvent and draw a properly scaled image, right?
Yes ;) Subclass QLabel and scale the Pixmap properly in resizeEvent();

wysota
8th September 2009, 09:09
You can probably also do it using "heightForWidth".

Executor
11th June 2011, 15:29
Hi! I was just searching how to solve this problem, and googling brings me to this post, so sorry for necroposting.

Another solution is available when you know if the image is wider than taller or vice versa. For the first case - apply vertical layout, than add vertical spacer (below image), set image to scaled, set spacer sizeType = expanding, sizeHint.height = 65536 (some large value).

This works because:
<<
scaledContents : bool
This property holds whether the label will scale its contents to fill all available space.
When enabled and the label shows a pixmap, it will scale the pixmap to fill the available space.
>>