Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QLabel->setScaledContents() does not work



  • Hello friends, I have the following code:

    #include "dialog.h"
    #include "ui_dialog.h"
    #include <QMessageBox>
    #include <QFileDialog>
    Dialog::Dialog(QWidget *parent)
      : QDialog(parent)
      , ui(new Ui::Dialog)
    {
      ui->setupUi(this);
    
    }
    
    Dialog::~Dialog()
    {
      delete ui;
    }
    
    
    void Dialog::on_toolButton_clicked()
    {
      QString fileName=QFileDialog::getOpenFileName(this,"Abrir imagenes",
                                                    QDir::rootPath(),"Imagenes (*.jpg *.jpeg *.png)");
      if(fileName.isEmpty())
        {
          return;
        }
      ui->label->setPixmap(QPixmap(fileName));
      ui->label->setScaledContents(true);
    
    }
    

    what I want is that when loading an image in the QLabel it adjusts to the size of the control but it doesn't work, I already put it in the constructor but it didn't work either; I tried to mark the property in the graphic designer but nothing, I would like to know why it is not working.


  • Lifetime Qt Champion

    #include <QtWidgets>
    int main(int argc, char **argv)
    {
        QApplication app(argc, argv);
    
        QString fileName=QFileDialog::getOpenFileName(nullptr, QString(), QString(), "Imagenes (*.jpg *.jpeg *.png)");
        QLabel lbl;
        lbl.setPixmap(QPixmap(fileName));
        lbl.setScaledContents(true);
        lbl.show();
    
        return app.exec();
    }
    

    This is working fine for me - an image set on the label is scaled and resized when I resize the label.



  • My guess is that it is because the OP is trying to modify the pixmap in a label managed from within a dialog. The dialog is probably setting some constraints that override the setScaledContent() call.


Log in to reply