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 -

setAutoFillBackground(true);
QPalette palette;
palette.setBrush(QPalette::Window, QBrush(QPixmap(":/images/bg.png")));
this->setPalette(palette);


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;
QWidget::paintEvent(pe);

(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;
styleOption.init(this);
QPainter painter(this);
style()->drawPrimitive(QStyle::PE_Widget, &styleOption, &painter, this);


If interested, you may go through the relevant thread.