Transparent QWebView (or QWebPage)

If you use QWebView, do you know how make its background to be translucent? Apparently, the trick is not so well known, hence I decide to share it here.

Basically it boils down the following code snippet:

QPalette palette = view->palette();
palette.setBrush(QPalette::Base, Qt::transparent);
view->setAttribute(Qt::WA_OpaquePaintEvent, false);

The first three lines set a new transparent brush for the page. This is necessary so that all the painting is blended properly. The last one ensures that the web view is not opaque, i.e. it does not paint all the pixels contained in its rectangle. Opaque paint event for QWebView is the default, most of the time you want to have a web page with typical normal background color, either set by the web page or something you specify as the fallback color.

If you combine QWebView see-through background with top-level widget opacity feature (see what Samuel wrote about this some time ago), you will get something like the following screenshot (the wallpaper image is Soft Green, from Valient Gough). Neat, isn't it? Note that of course it requires a window system which supports composition, e.g. modern X11 window manager, recent versions of Windows, and so on.

As usual, the code for this short example is available from the git repository, just check the transparentweb subdirectory. Again, I already prepared both the Qt/C++ and Python (via PyQt) versions. Enjoy!

Blog Topics: