How to Emit signals from javascript to qml

aleks_misyuk picture aleks_misyuk · Jan 2, 2012 · Viewed 12.5k times · Source

I want to emit signal from javascript-file and receive it in qml-file (To find when time-consuming operation will finished).

How can I do it?

Answer

Peace Makes Plenty picture Peace Makes Plenty · Sep 14, 2013

Neither Alex's nore Raja's solutions really answer the question. Alex's consists in calling directly from the javascript code the QML slot method, and Raja's consist in setting the value of a property of a QML object from the Javascript code. Both approaches negate the main advantage of the signal/slot mechanism which is that the signalling object does not need to know of the slot.

An approach closer to the spirit of the signal/slot mechanism is described in this blog post (not mine). It consists, within the javascript file, of creating a QML object (via the Qt.createQmlObject() function) the sole function of which is to contain the javascript's object signals. Signals are emitted from javascript through calling the internal QML objects signal (e.g. internalQmlObject.signalName()), and the javascript object signal can be connected in QML to QML slots with the usual connect mechanism via javascriptObject.internalQmlObject.signalName.connect(receiver.slotName).

An example adapted from the blog post is below:

javascript_object.js:

var internalQmlObject = Qt.createQmlObject('import QtQuick 2.0; QtObject { signal someSignal(int value) }', Qt.application, 'InternalQmlObject');

function doSomething() {
    internalQmlObject.someSignal(42);
}

test.qml:

import QtQuick 2.0
import 'javascript_object.js' as JavascriptObject

Rectangle {

    Rectangle {
        id: someComponent

        function someSlot(v) {
            console.log("Signal received " + v);
        }
    }

    Component.onCompleted: {
        JavascriptObject.internalQmlObject.someSignal.connect(someComponent.someSlot);
        JavascriptObject.doSomething();
    }
}

On execution it gives the following:

% qmlscene test.qml
Signal received 42