简体   繁体   English

在额外线程中运行 QML 方法

[英]Running QML Method in Extra Thread

I want to write a QML Item which can dynamically run functions + params in seperate threads.我想写一个 QML 项目,它可以在单独的线程中动态运行函数+参数。

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, ...包括连接的 cpp 对象、项目属性、...

QtConcurrent might help. QtConcurrent 可能会有所帮助。 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:然后像这样从 QML 调用它:

function testCall() {
    testObj.testFct(param, function(returnVal) {
        console.log("Asynchronous function returned: " + returnVal);
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM