QLabel is resizing when I set pixmap



  • Hi all,

    I have a QLabel which displays image frames as they arrive via socket. I'm using following code to scale the pixmap to label's size and set as pixmap:

    QPixmap pixmap = QPixmap::fromImage(image, Qt::ColorOnly);   
    qDebug()<< "Label size before setting a pixmap: \nWidth: " << ui->lblImage->width() << "; height: " << ui->lblImage->height();
     this->ui->lblImage->setPixmap(
                    pixmap.scaled(
                        ui->lblImage->size(),
                        Qt::IgnoreAspectRatio,
                        Qt::SmoothTransformation));
    qDebug()<< "Label size after setting a pixmap: \nWidth: " << ui->lblImage->width() << "; height: " << ui->lblImage->height();
    

    Here, lblImage is QLabel which is used to display my images.
    It's placed in the gridlayout, but I also tried vblayout and hblayout.

    The problem is, no matter which layout I use, my QLabel is growing everytime I set pixmap. However, debug output before and after setting pixmap shows same size, but next time when that slot is called the size is different.

    However, if I don't use scaled() method of QPixmap, the QLabel's size doesn't grow:

    this->ui->lblImage->setPixmap( pixmap);
    

    But in this case the image doesn't occupy the whole available space inside the QLabel.

    I tried to use following code before setting the pixmap

        this->ui->lblImage->setFixedWidth(image.width());
        this->ui->lblImage->setFixedHeight(image.height());
    

    And it solved the problem of QLabel's growing, however, QLabel doesn't resize when I resize the window.

    Btw, QLabel is inside the custom QWidget, that widget has other widgets too and they all are layed-out with gridlayout.
    And I didn't put my custom widget inside any QWindow or QDialog yet, just testing by calling my custom widget's show() method.

    So my question is how to make my label not grow when I set the pixmap? What is making it grow?


  • Moderators

    @umriyaev said in QLabel is resizing when I set pixmap:

    So my question is how to make my label not grow when I set the pixmap? What is making it grow?

    The reason is it's sizeHint, which gets updated when you set a pixmap and notifies the layout about it.
    You can try to set the size policy of the label:

    label->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
    


  • Thank you very much @raven-worx , it worked. :)

    What is the purpose of sizePolicy?


  • Moderators

    @umriyaev said in QLabel is resizing when I set pixmap:

    What is the purpose of sizePolicy?

    see the docs


Log in to reply
 

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