传递给 WorkerScript 源的参数

Arguments passed to WorkerScript source

我需要加载由 FileDialog 提供的文件路径的文档。 加载的文档相当长,所以我想显示一个 BusyIndi​​cator 在加载文档时。为了在加载我的文档时让 UI 旋转 ,我需要在 WorkerScript 中加载我的文档。现在我需要提供 .js 文件中由 WorkerScript::source 指向的函数的文件路径。我找不到任何方法。

有什么想法吗?

这是我的源代码:

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
}

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