Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

Tags:

c++

qt

qt4

qlabel

I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space available. The screen size is not always as big as the QPixmap.

How can I modify the QSizePolicy and sizeHint() of the QLabel to resize the QPixmap while keeping the aspect ratio of the original QPixmap?

I can't modify sizeHint() of the QLabel, setting the minimumSize() to zero does not help. Setting hasScaledContents() on the QLabel allows growing, but breaks the aspect ratio thingy...

Subclassing QLabel did help, but this solution adds too much code for just a simple problem...

Any smart hints how to accomplish this without subclassing?

like image 741
marvin2k Avatar asked Nov 21 '11 12:11

marvin2k


1 Answers

In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.

You can scale the pixmap by keeping its aspect ratio every time it changes:

QPixmap p; // load pixmap // get label dimensions int w = label->width(); int h = label->height();  // set a scaled pixmap to a w x h window keeping its aspect ratio  label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio)); 

There are two places where you should add this code:

  • When the pixmap is updated
  • In the resizeEvent of the widget that contains the label
like image 111
pnezis Avatar answered Sep 24 '22 23:09

pnezis