Image from resource file not loading in Qt
Asked Answered
S

3

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.

Searby answered 14/7, 2015 at 12:2 Comment(5)
Where is your resource file located?Barbed
all code/resource files are in C:\Users\...\projectSearby
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).Barbed
Works also on Win 8.1 and Qt 5.4Corticosteroid
Works for me. Do you get any error messages from rcc?Macaco
V
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");
Volsung answered 14/7, 2015 at 12:22 Comment(0)
M
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.

Maneuver answered 28/12, 2019 at 14:47 Comment(0)
L
2

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

Loganiaceous answered 15/5, 2017 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.