Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image in Qt to fit label size

I already tried several methods on displaying an image on a form, but none of them works how I would like.

I've read many places that the easiest way is to create a label and use that to display the image. I have a label, which size is specified by the layout, but if I load an image into it with a pixmap, the label is resized to the size of the image. If I use img tag as text or css background property, it won't display the whole image. What I would like to do is to load the image and fit into the label, not changing the label's size, but when I resize my window, and by that resizing the label as well, the image should be resized too so it will always fit into it.

If the only method is to get the label's size, and resize the pixmap so it would fit, and handle the resize event (signal), how could I resize the pixmap? I hope I won't need to save the whole thing into a QImage and create a pixmap from it each time.

Also, how can I center it? If it can't fit both the width and the height, I would like the smaller dimension to be centered.

Oh, and I don't want to use sliders to handle overflows.

like image 843
Máthé Endre-Botond Avatar asked Apr 13 '11 17:04

Máthé Endre-Botond


People also ask

How do I resize an image in QPixmap?

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));


3 Answers

Actually there is a very simple solution for this problem. There are two things you should modify:

  1. Set the scaled content to true (mentioned above)
  2. Set the label's size policy to ignored

    QLabel lblImage;
    
    lblImage->setPixmap( QPixmap( "big_image.jpg" ) );
    
    lblImage->setScaledContents( true );
    
    lblImage->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
    

If the lblImage is resizing automatically, the image will stretch to the size of the label.

like image 118
bukkfa Avatar answered Oct 12 '22 01:10

bukkfa


Does QLabel::setScaledContents(bool) help? There may also be some useful information in the image viewer example too.

like image 41
Arnold Spence Avatar answered Oct 12 '22 03:10

Arnold Spence


Keep a copy of your original pixmap around. Then connect the resized signal to a slot (or override the resizeEvent() function) that implements this :

lblImage->setPixmap(pixmap.scaled(lblImage->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
like image 22
Tim MB Avatar answered Oct 12 '22 02:10

Tim MB