Qt Hybrid Application Development:
An application that combines elements from diverse sources such as native and the web is considered to be a Hybrid Application. Needless to say developing UI in HTML/HTML5 with CSS/CSS3 is quite easy. The big challenge is to access the native layer from UI Layer. There are many tools in the open Source zone that helps to resolve this issue. Some of the notorious examples are phoneGap, QTWebKit Bridge.
Let me explain how QTWebKit Bridge works.
Quick Background refresh:
QWebPage, QWebFrame, and QWebView are the three objects that we need to be aware of.
QWebPage, and QWebFrame are of type QObject, and QWebView is of type Qwidget capable of displaying QWebPage.
Signal and Slots:
QT’s one of prominent feature is “Signals and Slots”. Slots are generally regular methods and it has no special meaning, except its signatures are kept in the table by MOC. To add more, it is synchronous and blocking call that the following code of ’emit’ statement occurs only after all slots are returned. To get more spice on the behaviour of signals and slots across thread, you can visit the below URL.
http://doc.qt.io/qt-4.8/threads-qobject.html
Well, to have a bridge between native and web , we need a native object and that object should be of QObject.
For Example, lets create the native object:
#ifndef NATIVEHELPER_H
#define NATIVEHELPER_H
#include <QObject>
class NativeHelper : public QObject
{
Q_OBJECT
public:
explicit NativeHelper(QObject *parent = 0);
Q_INVOKABLE void getFocus ();
signals:
updateUIFocus(int focusValue);
public slots:
void getFocusSlot();
};
1) Associate the QObject into UI/JavaScript:
In order to build the bridge, we need QObject that has to be bundled between JS and Native.
AddToJavaScriptWindowObject is a helper function from QWebFrame that is used to bundle.
For Example:
QWebFrame *myframe = myWebPage->mainFrame();
myframe->addToJavaScriptWindowObject(“ObjectNameInJS”, new NativeHelper());
2) Invoke Native Call from JS.
The slots defined in QObject can be invoked from JS.
For Example: In JS,
ObjectNameInJS.getFocusSlot() can be used.
3) Invoking JS Callback from Native.
Signals are used for this purpose. As we connect callbacks for the signals in native QT, we do in JS also. Look at the below code snippet.
NativeHelper.UpdateUIFocus.connect (Update_UI_Focus);
Where Update_UI_Focus can be defined as:
function Update_UI_Focus ( int focusValue ) -> Make sure the argument matches.
{
alert (“Qt Hybrid Application Test”);
}
QTWebKit Bridge makes job easier writing hybrid applications. In general, Embedded web applications lead to saving significant development cost and time to Market. But the flip side is, using luxury powerful features of Host platform. QTWebKit Bridge breaks this flip side, and comes handy while mixing both. That said, QTWebKit Bridge is definitely a boon to Embedded Web Application Development.