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.
Does QLabel::setScaledContents(bool) help? There may also be some useful information in the image viewer example too.
ui->label->setPixmap( pix.scaled( ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation) );
Worked like charm for my case (Qt 5.11).
pix
is aQPixmap
object with the original pixel count (e.g. constructed withQPixmap::fromImage(path)
).Actually there is a very simple solution for this problem. There are two things you should modify:
Set the label's size policy to ignored
If the
lblImage
is resizing automatically, the image will stretch to the size of the label.I will also answer my own question, but won't mark it as solution, because I requested a simple one which was given above. I ended up using a not too simple solution after all, so anyone who also needs to do something similar and has the time to play with it here's my final working code. The idea is to expand the QLabel and overload the setPixmap and the drawEvent methods.
QPictureLabel.hpp (header file)
QPictureLabel.cpp (implementation)
Usage : the same as using a normal label for displaying image wirthout the setScaledContents
Keep a copy of your original
pixmap
around. Then connect theresized
signal to a slot (or override theresizeEvent()
function) that implements this :