Sunday, April 14, 2013

Emitting signal from Javascript in QML application

While I was working on Ubuntu-Touch core app calendar, I wanted to emit signal from java script to QML code.

As such there is no official way provided by Qt framework, but we can try some workaround for this. Initially I used observer pattern to notify QML code from javascript. but I needed to wrote quite handful of code, and I did not liked the solution, I asked my team mates in calendar team and Frank suggested quite neat solution for this.

His suggestion was to create a temporary QtObject in javascript and use it for notification. Following is code for the same.

In following code, I created a QtObject in javascript with dataChanged signal defined in it.

eventsNotifier = Qt.createQmlObject('import QtQuick 2.0; QtObject { signal dataChanged }', Qt.application, 'EventsNotifier');
Now, we can use this object to emit signal to QML code, like this.

function someFunc() {
 ...
 ...
 eventsNotifier.dataChanged();
}
In QML code, we need to attach slot to dataChanged signal,like below.

    import "test.js" as TestJS

    function reload() {
        ...
        ...
    }
    Component.onCompleted: {
        TestJS.eventsNotifier.dataChanged.connect(reload);
    }
This is all, simple and neat.

No comments:

Post a Comment