11

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.

5
  • Where is your resource file located?
    – Amartel
    Commented Jul 14, 2015 at 12:16
  • all code/resource files are in C:\Users\...\project
    – didgogns
    Commented Jul 14, 2015 at 12:26
  • Odd. Your exact example works for me. I'm using Linux + Qt 4.8.6. Try one of Qt's examples ('System Tray Icon Example' contains qrc file).
    – Amartel
    Commented Jul 14, 2015 at 12:37
  • Works also on Win 8.1 and Qt 5.4
    – Miki
    Commented Jul 14, 2015 at 16:26
  • Works for me. Do you get any error messages from rcc? Commented Jul 14, 2015 at 18:26

3 Answers 3

8

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");
3

Here are the steps to how you can add a resource file .qrc to your project:

  • Image folder must be contained inside of the project folder
  • Right-click on the project file
  • Add New
  • Qt -> Qt Resource File -> press Choose -> name your file -> Finish.
  • After opening your .qrc file, press Add -> Add Prefix -> change prefix name if you want.
  • Add -> Add File -> and choose your images.
  • Go to mainwindow.cpp file and use the images from your .qrc file as follows:
ui->play->setIcon(QIcon(":/Playericons/icons8-pause-30.png"));

in my case, the image folder is called Playericons.

2

Did you remember to run qmake after adding the resource file?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.