Scaling QPixmap to fit Label

  • The following code is working, but the image is not scaled to fit the label.

    #include "dialog.h"
    #include "ui_dialog.h"
    Dialog::Dialog(QWidget *parent) :
        ui(new Ui::Dialog)
        QPixmap pix("C:/Programming/Qtsamples/Image_handling/IMG_6745.jpg");
        ui->label->setPixmap (pix);
        delete ui;
    How to make the image fit inside the label? (I tried several suggestions from the internet but they didn't work.)
    Thank you for your help.

  • Hi,
    setting scaledContents of the label should do it.



  • Qt Champions 2016

    adding to @Gerd
    You can also do

    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 

    If you need to scale it down to fit the are of the label.

  • Thank you. Both worked though I guess it is supposed to be

    int w = ui->label->width ();
    int h = ui->label->height ();
    ui->label->setPixmap (pix.scaled (w,h,Qt::KeepAspectRatio));

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.