Howto start a member function asynchronously from QML
-
In my QML, I'm calling a C++ member function i.e. myClass::recvFromQML() from QML like below
Action { onTriggered: myClass.recvFromQML(..); }
The recvFromQML() takes some time while processing and UI doesn't respond until the function is finished. I want to do that asynchronous so that my GUI doesn't stop.
Normally one create threads for asynchronous activities, but as I'm calling a member function of myClass ; whats option do I've ? Is their a simpler way of doing this in QT ?
-
-
Okay so I've created a WorkerScript like below:
WorkerScript.onMessage = function(message){ //Some JS code myClass.recvFromQML (...) // This is not recognized in the new thread
I've exposed this class as below in my main.cpp
Engine.rootContext()->setContextProperty("myClass", &obj);
How can i pass myClass.recvFromQML() to script.mjs
-
@pingal
whats the type of the "myClass" class exactly and what do you want to do with it?have you tried passing it as parameter like in the doc example?
myWorker.sendMessage({ 'myClass': myClass })
and in the worker:
WorkerScript.onMessage = function(message) { // ... long-running operations and calculations are done here WorkerScript.sendMessage({ 'myClass': 'myClass = ' + message.myClass }) }
-
myClass is derived from a QObject which has a member function i.e. recvFromQML() whose function is to send some data using a socket. The process is slow therefore I want it to happen async once invoked from QML.
So far I've tried passing it as parameter like below in my QML file
myWorker.sendMessage({'someString': x, 'myClass':myClass});
and in the worker:
WorkerScript.onMessage = function(message){ var someStr = message.someString; // This works message.myClass.recvCmdFromQml(...) // This doesn't }
QT returns the following error
qrc:/script.mjs:13: TypeError: Cannot call method 'recvCmdFromQml' of undefined
P.S: The documentation says "the script.mjs in the above example cannot access the properties, methods or other attributes of the QML item, nor can it access any context properties set on the QML object through QQmlContext".
So how would one call the invokable function from within script.mjs -
@pingal
okay,P.S: The documentation says
thats why i suggested passing the instance as a parameter, but this unfortunately doesnt seem to work.
Anyway you can move the threading to the C++ side and invoke a signal on the object once you task has finished.