Question

I tried to set an image to a Qt pushbutton using this widely known code.

QPixmap *pic = new QPixmap(":/images/logo.png");
QIcon *icon = new QIcon(*pic);
ui->pushButton->setIcon(*icon);
ui->pushButton->setIconSize(QSize(pic->width(), pic->height()));

Here's my qrc file

<RCC>
    <qresource prefix="/images">
        <file>images/logo.png</file>
    </qresource>
</RCC>

Even though the program compiles, always a runtime exception occurs at

QPixmap *pic = new QPixmap(":/images/logo.png");

When I tried printing *pic on output console, it showed that pic = QPixmap(QSize(0, 0) ). i.e. it is null. Any ideas as to where I went wrong?

Thanks in advance!

Was it helpful?

Solution

Please don't use pointers there.

You don't even have to create a QPixmap object and then use that to create a QIcon object. QIcon has a constructor that takes a file name as a parameter. But that's up to you. Also check your resource location. It looks like it should be :/images/images/logo.png

QPixmap pix(":/images/images/logo.png");
QIcon icon(pix);
ui->pushButton->setIcon(icon);
ui->pushButton->setIconSize(pix.size())

OTHER TIPS

If you use an alias in your resource definition, using the resource is a little easier: -

<RCC>
    <qresource prefix="/images">
        <file>images/logo.png</file>
        <file alias="logo">images/logo.png</file>
    </qresource>
</RCC>

Then you can reference the resource via its alias and if you change the image in the resource, you won't need to change the code: -

QPixmap image(":/images/logo");
QPushButton* pPushButton = new QPushButton(QIcon(image));

Or if the button is already defined: -

pPushButton->setIcon(QIcon(image));

I think you should call:

QPixmap *pic = new QPixmap(":/images/images/logo.png");

because you already set the prefix /images.

Is your Resource properly initialized? You might try this: (from the docs)

If you have resources in a static library, you might need to force initialization of your resources by calling Q_INIT_RESOURCE() with the base name of the .qrc file. For example:

 int main(int argc, char *argv[])
 {
     QApplication app(argc, argv);
     Q_INIT_RESOURCE(graphlib);
     ...
     return app.exec();
 }

EDIT More important:

QPixmap assumes a 'images' prefix. Try QPixmap(":/logo.png");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top