Why doesn't setting the pixmap of a QLabel work?

Dany Joumaa picture Dany Joumaa · Jan 2, 2011 · Viewed 7.3k times · Source

I've created a subclass of QLabel that I intend to use in a QGraphicsView. It serves as a movable "point" that one can click on and drag around the graphics view.

Creating the custom class and having it displayed in the graphics view hasn't been an issue; however, trying to get the custom QLabel to paint itself with the image I want isn't happening. The constructor for my custom QLabel class is like so:

TrackerPoint::TrackerPoint(QWidget *parent) :
    QLabel(parent)
{
    this->setFixedSize( 40, 40 );
    QPixmap pixmap( ":/images/target.png" );
    this->setPixmap( pixmap );
    this->setMask( pixmap.mask() );
}

I've ensured that the images directory exists in the working directory that the application is run from. If it is relevant at all, my QRC file is like so:

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

I've been trying to deal with this problem for days -- any ideas as to why the image isn't appearing would be lovely. (Does it have to do with the fact that I'm setting a pixmap in the constructor of the QLabel?)

Answer

rohanpm picture rohanpm · Jan 2, 2011

You have:

<qresource prefix="/images">
<file>images/target.png</file>
</qresource>

I think that this will result in a double images in the resource path, i.e. :/images/images/target.png. To fix that, either remove the prefix="/images" or put alias="target.png" in the file tag.

To make it clearer where the error is, you could write your code so that it uses QPixmap::load, since that can be checked for errors:

QPixmap pixmap;
if (!pixmap.load( ":/images/target.png" )) {
    qWarning("Failed to load images/target.png");
}
this->setPixmap( pixmap );

Or you could go even further and use QImageReader which can give detailed error messages.