qtqimageqt-resource

Image from resource file not loading in Qt


I'm trying to insert an image to my program via resource file, which is like:

<RCC>
    <qresource prefix="/">
        <file>green.png</file>
        <file>other files</file>
    </qresource>
</RCC>

and when I'm trying to load it using QImage or QPixmap, like:

QImage *green = new QImage(":/green.png");
if(green->isNull()) qDebug("null");

I always see that null message, indicating that I'm doing something wrong.

One solution may be using absolute path like:

<file>C:\\Users\\user\\Documents\\project\\green.png</file>

which works of course, but I'd prefer implement it using resource file.


Solution

  • Your problem would be solved if your png files are located in the same folder as .pro, .qrc, and .cpp files of your project.

    Usually it is convenient to put all images to special sub-folder, Resources for example. And your .qrc file would look like this:

    <RCC>
        <qresource prefix="/">
             <file>Resources/green.png</file>
            <file>Resources/other files</file>
        </qresource>
    </RCC>
    

    And you can use it in your .cpp file like this:

    QImage *green = new QImage(":/Resources/green.png");