Subnavigation

Google Suggest made easy

According to the FAQ, Google Suggest "guesses what you're typing and offers suggestions in real time". You can try it easily, just go to Google search page with the suggest feature and start typing something in the search field. Wouldn't it be nice if we can have that feature (where it makes sense) in our Qt-based applications? For example, the search box in the web browser demo is one candidate. In fact, that is one little feature I plan to add to the browser demo for Qt 4.6.

Since it will be quite some time until Qt 4.6 shows up, I thought I'd simplify the reference implementation and make it as an example. Since there is no official API for Google Suggest, we will use the trick (as explained in many places before) of parsing the XML returned by Google for certain search term. For example, "qt software" will give the following exemplary result.

<toplevel>
<CompleteSuggestion>
<suggestion data="qt software download"/>
<num_queries int="633000"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="qt software nokia"/>
<num_queries int="441000"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="qt software development"/>
<num_queries int="716000"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="qt software toolkit"/>
<num_queries int="446000"/>
</CompleteSuggestion>
</toplevel>

Quite simple, isn't it? An instance of QXmlStreamReader and a dozen of lines are all we need for a quick-and-dirty parser for this piece of XML. For the pop-up, two-column list is necessary. Intentionally I refrained from using QCompleter nor Model/View for the sake of keeping the code as readable as possible. Once the user picks a search term, the default browser is launched (via QDesktopServices) with the proper Google search URL for that particular term.

Get the example from the usual git repository. Don't want to use git? Get snapshot (105 KB) and unpack it. You can use Qt >= 4.4.

Careful readers might notice that I included the DragMove Charm. Indeed, this makes the search box movable by just dragging it around. Since there is no title bar and thus there is not a close button, just press Escape if you want to quit.

The obligatory screencast (only 11 seconds) follows. Or watch it directly on YouTube or blip.tv or grab the Ogg Theora video (450 KB).

As an exercise for the reader, rewrite the parsing code to use XLST 2.0 instead (it is new in QtXmlPatters in Qt 4.5). And while you are there, you can fix the parser so that it handles the XML properly (not just quick skipping the elements). In addition, forming the right URLs (both for suggestion and launching the browser) can use some encoding fixes as well. And who else also wants Yahoo! search suggest?


Blog Topics:

Comments