How to load an image in a QPixmap to display it in a QLabel

10,844

Two things to do:

  1. Check if QFile can open that resource and read it. Dump it out to a file on disk.

    QFile fi(":/img/Interrogation.png");
    QFile fo(QDir::homePath() + QDir::separator() + "Interrogation.png");
    if (!fi.open(QIODevice::ReadOnly)) {
      qWarning() << "Can't open the resource" << fi.fileName();
      return;
    }
    if (!fo.open(QIODevice::WriteOnly)) {
      qWarning() << "Can't open the output" << fo.fileName();
      return;
    }
    fo.write(fi.readAll());
    
  2. Check the format of whatever is dumped out to disk to ensure that it's a valid png file. You can open it in an image editor, for example - just be sure to verify that the extension agrees with the contents. A valid JPEG file with .png extension will fail to load.

Share:
10,844
Chax
Author by

Chax

Updated on June 04, 2022

Comments

  • Chax
    Chax almost 2 years

    I've read multiple article on it and it still does'nt work!!

    I know I'm doing it right, but for some reason it does'nt work.

    Here's my code :

    myIcon = new QLabel();
        QPixmap myPixmapForNow;
        if(!myPixmapForNow.load(":/img/Interrogation.png")){
            qWarning("Failed to load");
        }
        myIcon->setPixmap(myPixmapForNow);
    

    It tells me that the file failed to load each time.

    What i want to do with this is to display an image that will have a tooltip and explain what the button next to it does. Basicaly, I'm looking for a way to display an image that have a tooltip programmed in it.

    I'm a beginner and honestly the concept of looking in folders is a bit abstract for me. If you have a blog or something to propose, i'll be willing to read it. I've been looking for one and I have'nt found any good one that explain the concept and how to do it.

    If you have a solution for my problem please explain it. Nothing better than explanation :)

    Thanks