QML:在并行线程中运行函数

Rob*_*tex 5 parallel-processing multithreading qml

在我的代码中,我在循环中创建16x16按钮,这需要几秒钟.

onCreateField:
{
    for(var i=0;i<fieldWidth;i++)
    {
        for(var j=0;j<fieldHeight;j++)
        {
            createButton(i, j);
        }
    }
}

function createButton(x, y)
{
    __buttonX = x;
    __buttonY = y;

    __component = Qt.createComponent("GameButton.qml");

    if(__component != null)
        continueButtonCreation();
    else
        __component.ready.connect(continueButtonCreation);
}

function continueButtonCreation()
{
    var button = __component.createObject(field, {"row": __buttonY, "column": __buttonX});

     if (button == null) {
         // Error Handling
         console.log("Error creating object");

         return;
     }

     updateValveState.connect(button.stateUpdated);
     button.buttonClicked.connect(buttonClicked);

     field.clearField.connect(button.release);
}
Run Code Online (Sandbox Code Playgroud)

创建按钮的功能运行时,应用程序冻结.我希望在此函数运行时显示加载动画.那么,如何在并行线程中运行此函数以避免冻结?

最好的问候,尼克

Ami*_*mar 10

要在线程中工作,您有两种可能的方法:

  1. 阅读有关WorkerScript元素的信息.它允许您通过将javascript函数作为线程运行来执行某些操作.

注意:正如文档中给出的那样,有一个限制:

由于WorkerScript.onMessage()函数在单独的线程中运行,因此JavaScript文件将在与主QML引擎分开的上下文中进行评估.这意味着,与导入QML的普通JavaScript文件不同,上例中的script.js无法访问QML项的属性,方法或其他属性,也无法通过QDeclarativeContext访问QML对象上设置的任何上下文属性. .此外,可以传递给工作脚本和从工作脚本传递的值的类型也有限制.有关详细信息,请参阅sendMessage()文档.

只要看看,如果您的特定用例符合要求.

2.实现像C++线程一样繁重的功能.每当需要时,生成一个信号以在C++端启动该线程.完成后,如果需要,将数据从C++传回Qml.