Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Scaling QPixmap to fit Label
QtWS25 Last Chance

Scaling QPixmap to fit Label

Scheduled Pinned Locked Moved Solved General and Desktop
scalingqpixmap
4 Posts 3 Posters 37.3k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    gabor53
    wrote on 15 Dec 2015, 16:51 last edited by
    #1

    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) :
        QDialog(parent),
        ui(new Ui::Dialog)
    {
        ui->setupUi(this);
    
        QPixmap pix("C:/Programming/Qtsamples/Image_handling/IMG_6745.jpg");
        ui->label->setPixmap (pix);
    }
    
    Dialog::~Dialog()
    {
        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.
    1 Reply Last reply
    0
    • G Offline
      G Offline
      Gerd
      wrote on 15 Dec 2015, 20:31 last edited by
      #2

      Hi,
      setting scaledContents of the label should do it.

      ui->label->setScaledContents(true);

      Regards
      gerd

      1 Reply Last reply
      2
      • M Offline
        M Offline
        mrjj
        Lifetime Qt Champion
        wrote on 15 Dec 2015, 21:15 last edited by
        #3

        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 
        label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio);
        

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

        1 Reply Last reply
        0
        • G Offline
          G Offline
          gabor53
          wrote on 15 Dec 2015, 23:13 last edited by
          #4

          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));
          
          1 Reply Last reply
          0

          3/4

          15 Dec 2015, 21:15

          • Login

          • Login or register to search.
          3 out of 4
          • First post
            3/4
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • Users
          • Groups
          • Search
          • Get Qt Extensions
          • Unsolved