传递给WorkerScript源的参数

时间:2017-08-16 10:09:38

标签: qml qtquick2 qtquickcontrols2

我需要加载文件路径由 FileDialog提供。文档加载时间很长,所以我想在加载文档时显示 BusyIndi​​cator 。为了在加载我的文档时获得 UI旋转,我需要在 WorkerScript 中加载我的文档。现在我需要将文件路径提供给 WorkerScript :: source 指向的 .js 文件中的函数。我找不到任何办法。

有什么想法吗?

这是我的源代码:

WorkerScript
{
    id: importScanWorkerScript
    source: "script.js"
}

FileDialog
{
    id: importScanDialog
    visible: false
    title: "Import a [scan] file"
    folder: "/home/arennuit/Desktop/living_room_traj0n_scannedScene"
    nameFilters: [ "STL files (*stl)" ]
    selectedNameFilter: "STL files (*stl)"
    onAccepted:
    {
        importScanDialog.visible = false;
        busyIndicator.running = true;
        uiController.onImportScanDevMenuClicked(importScanDialog.fileUrl);
        busyIndicator.running = false;
    }
}

BusyIndicator
{
    id: busyIndicator
    running: false
    anchors.centerIn: parent
}

1 个答案:

答案 0 :(得分:1)

WorkerScript允许您将自定义对象发送到线程并且还可以返回自定义对象,我想文档非常清楚。所以问题的答案是WorkerScript.sendMessage()。在下面的简单示例中,WorkerScriptmain.qml接收随机的迭代次数,因此生成并发回由main.qml显示的生成文本。等待时GUI不会冻结:

<强> main.qml

import QtQuick 2.9
import QtQuick.Window 2.0
import QtQuick.Controls 2.2

Window {
    id: window
    width: 600
    height: 400
    visible: true

    ScrollView {
        id: view
        anchors.fill: parent
        clip: true
        TextArea {
            id: myText
            text: ""
            enabled: false
        }
    }
    Component.onCompleted: {
        var cnt = 1000 + Math.round(Math.random() * 1000);
        myText.text = "Please wait, generating text (" + cnt + " characters) ...";
        myWorker.sendMessage({count: cnt});
    }

    WorkerScript {
        id: myWorker
        source: "script.js"
        onMessage: {
            myText.text = messageObject.reply;
            myText.enabled = true;
            spinner.running = false;
        }
    }

    BusyIndicator {
        id: spinner
        anchors.centerIn: parent
        running: true
    }
}

<强>的script.js

function pause(millis)
{
    var date = new Date();
    var curDate = null;
    do { 
        curDate = new Date(); 
    } while((curDate - date) < millis);
}

WorkerScript.onMessage = function(message) {
    var txt = "";
    var count = message.count;
    for(var i = 0;i < count;i ++)
    {
        var ch = 97 + Math.round(Math.random() * 25);
        txt += String.fromCharCode(ch);
        var eol = Math.round(Math.random() * 30);
        if(eol === 1)
            txt += "\r\n";
        else if(!(eol % 5))
            txt += " ";
        pause(10);
    }
    WorkerScript.sendMessage({ 'reply': txt })
}