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
Forum Updated to NodeBB v4.3 + New Features

Scaling QPixmap to fit Label

Scheduled Pinned Locked Moved Solved General and Desktop
scalingqpixmap
4 Posts 3 Posters 37.7k Views 1 Watching
  • 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 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 last edited by
      #2

      Hi,
      setting scaledContents of the label should do it.

      ui->label->setScaledContents(true);

      Regards
      gerd

      1 Reply Last reply
      2
      • mrjjM Offline
        mrjjM Offline
        mrjj
        Lifetime Qt Champion
        wrote on 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 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

          • Login

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