Sunday, May 3, 2009

Qt : set background image of a custom widget

When I first needed to get a background image for my custom widget in Qt 4.5, 2 solutions came to my mind. Here I have described how I failed with those seemingly working solutions with no satisfactory explanation, let alone a compelling one, and the working solutions suggested by the people at QtCentre forum.

(1)Using QPalette

Solution that does not work:

In the constructor of my custom widget -

QPalette palette;
palette.setBrush(QPalette::Window, QBrush(QPixmap(":/images/bg.png")));

As I said before, QPalette with brush derived from the background image did not work.

Solution that works:

Override QWidget's paintEvent(QPaintEvent* pe) method -

QPainter* pPainter = new QPainter(this);
pPainter->drawPixmap(rect(), QPixmap(":/images/bg.png"));
delete pPainter;

(2) Using StyleSheet

Solution that does not work:

It's intuitive that setting stylesheet property background-image should be sufficient to get a background image for your custom widget (that inherits QWidget class).

setStyleSheet("background-image: url(:/images/bg.png)");

Solution that works:

- Set style sheet with the above statement in the constructor.
- Override QWidget's paintEvent(QPaintEvent* pe) method -

QStyleOption styleOption;
QPainter painter(this);
style()->drawPrimitive(QStyle::PE_Widget, &styleOption, &painter, this);

If interested, you may go through the relevant thread.


Daniel Albuschat said...

I've stumbled upon this a few times, too. The trick is to not derive from QWidget, which does not support background-image, but from QFrame instead. I can't count the times (well, it's probably three) that I was about to byte into my keyboard because I couldn't figure out why the background-image is not showing, until I realized that this only works for QFrame...

Anonymous said...

@ Daniel:

Thank you so much for the QFrame hint!!! My keyboard was in big dange as well :-)

Anonymous said...

The most ennoying thing is that it even seems to work in the Designer for QWidget derived classes, while it doesn't when you build it.

thanks for the hint,

Rodolphe said...

Thanks for your code

Anonymous said...

Thanks for this post it will helped me a lot

priofacebook said...

thanks very much .This is very helpful.

Anonymous said...

Thank you so much.. I struggled for 1hr on setting background image for my entire keyboard.. you solutions really got me out of trouble..

Thanks once again.. :-)

Anonymous said...

Thank you so much!!!