Image Viewer Scaling
-
Hello. I'd like to display an image that scales to the size of the container but also keeps it's aspect ratio (meaning the container will have margins in either height or width if it's not the same aspect ratio as the image). I know I sound lazy in not figuring this out for myself, but all the examples and things I've tried have not quite gotten me there yet. For example the "imageviewer" example app almost does what I want with a Qlabel in a Qscrollarea .. but it doesn't maintain the aspect ratio (it just fills it in both dimensions). I've also tried playing with things like: Qt::KeepAspectRatio, Qt::SmoothTransformation .. and while these seem to work initially, I'd also like things to stay updated when I resize the GUI (which these do not do automatically).
Any advice would be greatly appreciated! Thanks.
-
OK, not sure if this is the best way, but this seems to do what I want (and like Christian mentioned this should happen when a new image is loaded and when the widget is resized):
label_image is a QLabel
pix_orig is the original pixmap which I keep around in case I ever want to resize "pix manually" (probably not necassary to do this)QPixmap pix = pix_orig; ui->label_image->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); ui->label_image->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->label_image->setPixmap(pix.scaled( ui->label_image->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
-
When a widget is resized, QWidget::resizeEvent() is called which yo can overwrite.
-
@Christian-Ehrlicher OK, thanks. That's cool .. but not sure how I want to render and keep the aspect ratio to begin with.
-
OK, not sure if this is the best way, but this seems to do what I want (and like Christian mentioned this should happen when a new image is loaded and when the widget is resized):
label_image is a QLabel
pix_orig is the original pixmap which I keep around in case I ever want to resize "pix manually" (probably not necassary to do this)QPixmap pix = pix_orig; ui->label_image->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); ui->label_image->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui->label_image->setPixmap(pix.scaled( ui->label_image->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));