View Full Version : QWidgets and QPixmaps and Stylesheets .... oh my.

5th June 2009, 05:01
using QT4.5, I have a class derived from QWidget. It uses stylesheets to loads a bitmap into the background. This stylesheet is loaded at runtime and is user made.

class MyClass : public QWidget
MyClass (QWidget *pParent ) : QWidget( pParent) {}
~MyClass () {}
virtual void paintEvent(QPaintEvent *ev);

ex from a stylesheet file:

MyClass {
background-image: url(images/background.png);

in my app, I load the stylesheet as runtime using something like:

QFile file( "thesheet.qss" );
file.open( QFile::ReadOnly );
QString styleSheet = QLatin1String( file.readAll() );

The background loads fine from the stylesheet....

But in my MyClass paintEvent() code, I want to be able to access the QPixmap that the base QWidget class creates for the background (... but it seems that QWidget doesn't provide any accessors.).

I know I can pre-parse the stylesheet to find the image filename, or I could use an inelegant hack and render the widget to a Painter using:


but isn't there a simple way to access the background image?

5th June 2009, 05:54
hmmm.... just noticed QWidget's backgroundRole() method....

5th June 2009, 08:50
for the time being I'm using the following
little hack within my myClass code to get the background.

QPalette p = this->palette();
QBrush bk = palette.background();
QPixmap pm = bk.texture();
//do some mods on background pixmap, stored in "pm"
// redraw the image in QRects defined earlier...
painter.drawPixmap( qr1, pm, qr2 );

still not happy using an ugly hack like this when access to stylesheet defined properties should be easily accessed within the classes themselves...