Night-mode in QWebView

An interesting feature of a navigation system (so I was told, I don't own a car) is the so-called "night mode". Basically the display is adjusted so that the text and the map become more readable under low ambient light condition. An easy trick to do this is by inverting the color, just like what Mac OS X can do for the whole desktop.

Thanks to QPainter, it is fairly easy to do that in just a few lines of code. Basically we need to use a proper composition mode. If you think composition modes are like black magic, here is a chance to understand a bit of it. As you read the documentation on QPainter::CompositionMode_Difference or CompositionMode_Exclusion, you will find that Painting with white inverts the destination color. Voila! That is exactly the cheating path that we have to use.


The super-short example for color inversion is in the Graphics Dojo repository under the webnightmode directory (available for both Qt/C++ and PyQt). Although the trick here is illustrated for QWebView, of course it is suitable for other widgets, too (see Henrik's yesMan example). Note that not every paint engine/device supports QPainter::CompositionMode_Difference, hence why in the code I force the use of raster graphics system under X11.

Note that an actual implementation of a night-mode feature is likely more complicated than just a color inversion method (feel free to suggest or brainstorm the ideas for such an algorithm). The overall brightness and constrast should be taken into account. Likely this requires an adventure in the non-RGB color space, something that is outside the scope of this example. Most of the cases however, you can get away with the discussed trick.

Exercise for the brave readers: use selectors (CSS or jQuery) to find the map element, then invert that element only.


Blog Topics:

Comments