[Qt] Qlabel::setScaledContents(true); invalid in Qlayout

Add a picture to the Qlabel and make the picture adaptive to the size of the Qlabel

    QPixmap picture;
    picture.load("./1.jpg");
    ui->label->setScaledContents(true);//图片自适应label大小
    ui->label->setPixmap(picture);

Qlabel::setScaledContents(true); invalid in layout

The solution is to scale the Qixmap before setPixmap

    //QLabel label1 = new QLabel("hello",this);
    QString path = QCoreApplication::applicationDirPath();
    path = QFileDialog::getOpenFileName(this, "open image", path, tr("Images (*.png *.xpm *.jpg)"));
    QPixmap pixmap(path);
    //pixmap = pixmap.scaled(label1->size());//没有考虑QLabel的线宽,导致label1比加载图片前大了两个线宽
    pixmap = pixmap.scaled(label1->width()-label1->lineWidth()*2,
label1->height()-label1->lineWidth()*2);
    label1->setPixmap(pixmap);

demo code download

https://download.csdn.net/download/u010168781/10361038

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325523070&siteId=291194637