QML:在并行线程中运行函数 [英] QML: running functions in parallel threads

查看:411
本文介绍了QML:在并行线程中运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my code I'm creating 16x16 buttons in cycle and this take few seconds.

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);
}

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

While function that creating buttons runs, app freezes. I want to show loading animation while this function runs. So, how to run this function in parallel thread to avoid freezing?

推荐答案

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

To do work in threads you have two possible approaches :

  1. 阅读 WorkerScript 元素.它允许您通过将javascript函数作为线程运行来执行某些操作.
  1. Read about the WorkerScript element. It allows you to perform certain operation by running the javascript functions as threads.

注意:如文档中所述,虽然有一个限制:

Note: As given in the documentation, there is a restriction though :

由于WorkerScript.onMessage()函数在单独的位置运行 线程,则在与以下内容不同的上下文中评估JavaScript文件 主要的QML引擎.这意味着与普通的JavaScript不同 导入到QML的文件,即上例中的script.js 无法访问QML的属性,方法或其他属性 项目,也不能访问在QML对象上设置的任何上下文属性 通过QDeclarativeContext.此外,在 可以传入和传出辅助脚本的值的类型. 有关详细信息,请参见sendMessage()文档.

Since the WorkerScript.onMessage() function is run in a separate thread, the JavaScript file is evaluated in a context separate from the main QML engine. This means that unlike an ordinary JavaScript file that is imported into QML, the script.js 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 QDeclarativeContext. Additionally, there are restrictions on the types of values that can be passed to and from the worker script. See the sendMessage() documentation for details.

请看看,是否适合您的特定用例.

Just see, if for your particular use case it suits the requirement.

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

2 . Implement the functionality which are heavy as C++ threads. Whenever required, generate a signal to start this thread on the C++ side. When done, pass back the data from C++ to Qml , if required.

这篇关于QML:在并行线程中运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆