c++imageqtpixmap

Image for QPixmap can't be found


I want an image to be shown in the same window if I click on a button. But the image can't be found, no matter if it is in the same directory or I write down the whole path. I saw several ways to integrate a picture and thought this was the best one:

MyApp::MyApp(QWidget *parent)
    : QWidget(parent)
{
    QPushButton *button = new QPushButton("&Randomize!");
    gitterlayout->addWidget(button, 5, 0);

    connect(button, SIGNAL(clicked()), this, SLOT(Randomizer()));
}

void MyApp::Randomizer()
{

    QLabel* bild = new QLabel;
    QPixmap pixmap("question.png"); // the important part, the picture is in my project folder
    if(!pixmap.isNull())
    {
        bild->setPixmap(pixmap);
        bild->show();
    }
    else
    {
        qDebug() << "Cannot find picture"; // I always get this message
    }

    /* I want this question image to appear because once you click on the button, 
       a text will be copied to the clipboard and you can't see it until you paste it 
       (I left it out for this topic) */
}

If I use QPixmap pixmap("C:/myproject/question.png"); (the full path) It doesn't work as well.


Solution

  • Because Qt uses the build folder("C:\\build-myproject-5.4.2-debug" in this case) as the working folder by default( build-myProject-5.4.2-release if you run under the release mode). You can change it by swithing to Projects mode and balabala. Or just put your pic into that working folder. On windows, the path delimiter should be '\' rather than '/', which usually causes a lot of troubles.

    All your resources should be put here when running through Qt creator.