2017-08-16 18 views
0

我需要加载文件,文件路径由FileDialog提供。该文档的加载时间很长,所以我想在加载文档时显示BusyIndi​​cator。为了在加载我的文档时获得UI加速我需要加载我的文档WorkerScript。现在我需要为.js文件中的函数提供我的文件路径WorkerScript :: source。我找不到任何方式来这样做。传递给WorkerScript源的参数

有什么想法?

这里是我的源代码:

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

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

我真的,创建辅助线程不明白这一点,但[从这里](http://doc.qt.io/qt-5/qml-workerscript.html#restrictions),它似乎无法访问QML的项目属性,方法和属性(我能够加倍检查这在我的代码)。我的控制器是在主线程上下文中导入的C++ QObject(因为我所有的计算都是在C++中进行的)。如果我无法访问我的控制器,辅助线程有什么意义?我想这是我错过的东西... – arennuit

+0

你回答了最初的问题。我为[访问控制器]写了一个更具体的问题(https://stackoverflow.com/questions/45752428/workerscript-access-to-controller-class)。 – arennuit