ariya.io About Collections Archives

hybrid native+web: using dialog boxes

2 min read

After looking at some complex hybrid examples such as folder visualization and code editor, it’s time to take a step back and review some basic concept.

The following example is really simple, it should provide you a good starting point to explore the signal-slots handling in the web-to-native bridging. Basically we will trigger a native dialog from the JavaScript side of the application. Should you want to follow along, the whole code is in the usual X2 git repo (or the alternative repo), look under hybrid/nativedialog (you need Qt 4.6 or later versions).

To get a taste, here’s the screenshot first. I showed this for the first time during my presentation at Intel Elements 2011 in Bellevue, hence the choice of the sample message.

In the C++ side, we need to have the actual dialog implementation. For the sake of keeping it simple, here is the declaration:

class Dialog: public QObject
{
    Q_OBJECT
 
public:
    Dialog(QObject *parent = );
 
public slots:
    void showMessage(const QString& msg);
};

All we care for now is that showMessage() function, which would just call QMessageBox. In real-world application, you can use other types of standard Qt dialogs and possibly even create your own custom dialog.

void Dialog::showMessage(const QString &msg)
{
    QMessageBox::information(, "Information", msg);
}

Once we have the instance of the above Dialog class, we inject it into our web page using addToJavaScriptWindowObject as follow:

QWebFrame *mainFrame = webView.page()->mainFrame();
   mainFrame->addToJavaScriptWindowObject("Dialog", new Dialog);

Now, whenever you want to pop up the dialog, i.e. via the handler of that Show Message button (which is just a normal input element), call it like this:

Dialog.showMessage(document.getElementById('msg').value);

This is the simplest possible Qt and WebKit bridging example I can think of, so that’s all!

Related posts:

♡ this article? Explore more, check the archives, or follow me Twitter.

Share this on Twitter Facebook Google+

comments powered by Disqus