I created a label in my main window and its size is set to 200x300px. now on a button click i need to view a image in it. here is the slot function of the button.
void MainWindow::function1(){
QImage img;
img.loadFromData("test.jpg");
img = img.scaled(200, 300, Qt::KeepAspectRatio, Qt::SmoothTransformation);
label->setPixmap(QPixmap::fromImage(img));
}
the problem is this compiles without errors, but not displaying the image. insted when the button is pressed it says QImage::scaled: Image is a null image
in the IDE
im new in qt. I would be very thankful for any advice.
thank you
Using a QImage
is necessary if you are processing images outside of your GUI thread. Also the loadFromData()
function looks like it is used for passing in a large array of bytes, not the name of the file.
Here is how I would do it with a QPixmap.
QPixmap pix;
bool loaded = pix.load("test.jpg");
if(loaded == false)
{
label->setText("Failed to load test.jpg from" + QDir::currentPath());
}
else
{
pix = pix.scaled(200, 300, Qt::KeepAspectRatio, Qt::SmoothTransformation);
label->setPixmap(pix);
}
You may also want to replace 200 and 300 with label->width()
and label->height()
. Scaling a pixmap this way looks the best, but you can also just set the pixmap and then use label->setScaledContents(true)