My blog has been moved to ariya.ofilabs.com.

Tuesday, April 28, 2009

transparent QWebView and QWebPage

Seems that the trick to make a transparent QWebView or QWebPage is not very well known. So here is the magic incantation:

    view = new QWebView(this);
    QPalette palette = view->palette();
    palette.setBrush(QPalette::Base, Qt::transparent);
    view->page()->setPalette(palette);
    view->setAttribute(Qt::WA_OpaquePaintEvent, false);

Or grab it at http://gist.github.com/103126.

Here is the result (click to zoom). I put the famous TuxKiller wallpaper as the background for the main window. The central widget is set to a QWebView instance, using the transparent trick. As everyone loves Cube these days, that is the URL I am loading:

Note 1: of course this does not work if the web page explicitly sets the background color. For example, google.com (see its HTML source) forces a white background.

Note 2: with Qt 4.4's QtWebKit, you have to use the background brush instead of the base brush. This is changed in Qt 4.5 for consistency with the rest of Qt (it is mentioned in Qt 4.5.0 changes file).

7 comments:

maninalift said...

The roadsign should be animated, is it? None of the QWebKit based browsers animated the digging man (though they did a little better than Opera which didn't render the man at all and much better than KHTML which didn't render the svg at all). Firefox/Gecko was the only browser to render everything on my machine.

(though perhaps it didn't render everything as I have nothing else to compare it to)

lfranchi said...

thanks for the tip! i had actually tried to do this last week and failed. this works great :)

cheers.

Unknown said...

on the one hand: awesome! now it's transparent.

on the other hand: why isn't this the *default* behavior? why isn't there at a minimum some non-voodoo way to achieve this?

Ariya Hidayat said...

@maininalift: looks like a bug.

@Aaron: the default is always the tricky part, half of the planet will just hate it no matter what. Since opaque, non-transparent painting seems to be the common case, it's chosen to avoid the surprise.

Anyway, QWebPage::palette documentation already says "The base brush of the palette is used to draw the background of the main frame."

Rich Moore said...

I'd suggest that this should be covered in the docs. I for one wasn't aware of it.

Anonymous said...

Hi,

Thanks for this post, but I had a problem implementing this. I don't know what I did wrong, but to make it work I had to add another line:

view->setPalette(palette);

I hope this is useful to someone.

Terima Kasih

Unknown said...

thanks for the post,

but i also had to add the view->setPalette(palette) line to get it working.