Qt Academy has now launched! See how we aim to teach the next generation of developers. Get started
最新版Qt 6.3已正式发布。 了解更多。
最新バージョンQt6.5がご利用いただけます。 詳細はこちら

QWebView snap-scrolling

When you develop a web browser for a mobile platform, a D-pad or a mini trackball is usually the main in-page navigation input. In some browsers, going "down" scrolls the whole web page or jumps to the nearest (sensible) hyperlink. There is an interesting observation here. As you scroll to read e.g. a news site, your eyes are locked to the topmost part of the browser. Hence, a scrolling system that avoids "slicing" the content right at the top of the view will be useful. Your eyes are not distracted because it is easier to locate the "next-to-read" spot after the page scrolls.

If the above paragraph is not easy to understand, consider the following screenshot. Both windows show the mobile version of BBC News, after scrolling (I pressed the down arrow nine times). On the right side, the image is cut. On the left side however, the image is positioned so that it will be aligned properly. In fact, if I continue pressing down arrow key many times until I reach the section where there is no image anymore, it always scrolls and snaps each text line, which is very convenient as you read the text.


The example for doing this snap-scrolling is in the Graphics Dojo repository under the snapscroll directory (available for both Qt/C++ and PyQt). To keep the example as simple as possible, I implement the snapping when down arrow key is only. Ideally, you might want to handle e.g. the up arrow, as well as page up and page down. Furthermore, the snap threshold constant actually should be font size dependent to ensure smooth scrolling. If you try the code, sometimes it fails because it snaps only in one direction. If you really prefer the "magnet behavior" consider adding some intelligence to snap in both directions.

The code also shows how to find out the bounding boxes (of the DOM elements) in a particular area of interest QWebFrame::hitTestContent() (in Qt 4.6 we will have the full QWebElement solution for this). The code proves, it is sufficient (at least for this scrolling purpose) to check for a hit in several sample points in that area. Beside, if a 3x3 pixels image escapes our detection and will not be snapped, how does it matter anyway?

Happy snapping!


Blog Topics:

Comments