Reputation: 1
I want to write a QML Item which can dynamically run functions + params in seperate threads.
I imagine it to look like so:
import QtQuick 2.0
Item {
function runThread(fnc, params)
{
// run this fnc function with the given params in seperate thread without blocking ui
}
}
The functions which are getting executed must be able to access any states from my main engine. Including connected cpp objects, item properties, ...
Upvotes: 0
Views: 491
Reputation: 8277
QtConcurrent might help. Try something like this:
void TestObj::testFct(int someParam, const QJSValue &callback){
auto *watcher = new QFutureWatcher<int>(this);
QObject::connect(watcher, &QFutureWatcher<int>::finished, this, [this, watcher, callback]() {
int returnValue = watcher->result();
QJSValue cbCopy(callback);
QJSEngine *engine = qjsEngine(this);
cbCopy.call(QJSValueList { engine->toScriptValue(returnValue) });
watcher->deleteLater();
});
watcher->setFuture(QtConcurrent::run(this, &TestObj::testFctAsync, someParam));
}
Then call it from QML like this:
function testCall() {
testObj.testFct(param, function(returnVal) {
console.log("Asynchronous function returned: " + returnVal);
})
}
Upvotes: 1