问题描述
我有一个BusyIndicator,它应该在进行大量计算时旋转,并在完成计算时停止.
I have a BusyIndicator which should spin while heavy computations are happening and stop when the computations are done.
我认为WorkerScript是正确的选择,但是从这里 ,.js文件中的辅助(计算线程)似乎无权访问主要.qml线程的对象.
I thought WorkerScript was the right way to go but but from here, it seems that the secondary (computation thread) in the .js file does not have access to the objects of the primary .qml thread.
这是有问题的,因为我所有的计算都是通过由主线程实例化的Controller C ++定义的QObject执行的.
This is problematic as all my computations are performed through a Controller C++ defined QObject instantiated by the primary thread.
这是我的代码:
main.qml
import QtQuick 2.7
import QtQuick.Layouts 1.3
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Controls.Material 2.0
import QtQuick.Controls.Styles 1.2
import QtQuick.Dialogs 1.2
import LcQml 1.0
ApplicationWindow
{
id: window
UiController
{
id: uiController
}
WorkerScript
{
id: importScanWorkerScript
source: "importScanWorkerScript.js"
onMessage:
{
busyIndicator.running = false;
}
}
FileDialog
{
id: importScanDialog
visible: false
title: "Import a [scan] file"
folder: "MyScannedScenesFolder"
nameFilters: [ "STL files (*stl)" ]
selectedNameFilter: "STL files (*stl)"
onAccepted:
{
importScanWorkerScript.sendMessage({'filepath': importScanDialog.fileUrl})
busyIndicator.running = true;
}
}
BusyIndicator
{
id: busyIndicator
running: false
anchors.centerIn: parent
}
}
importScanWorkerScript.js
WorkerScript.onMessage = function(message)
{
uiController.onImportScanDevMenuClicked(message.filepath);
WorkerScript.sendMessage()
}
Pb::未在 importScanWorkerScript.js 中定义uiController.
Pb: uiController is not defined in importScanWorkerScript.js.
我是否应该了解WorkerScript仅能处理简单的情况?
Should I understand that WorkerScript can only handle simple situations?
推荐答案
您已经注意到,WorkerScript
无法访问UI控件.但是您单独的线程可以使用消息与主UI线程对话".对于我来说,它的工作方式与所有其他语言/框架完全相同.只要您想更新UI或对象,只需从线程发送消息即可.例如:
As you already noticed, WorkerScript
cannot access UI controls. But your separate thread can "talk" to the main UI thread using messages. As for me that works exactly as in all other languages/frameworks. Just send a message from the thread whenever you want to update UI or your object.For example:
WorkerScript.onMessage = function(message) {
WorkerScript.sendMessage({ 'action': 'start' })
// do some heavy task here
WorkerScript.sendMessage({ 'action': 'finish', 'data': somedata })
}
所以您的主要qml可能如下所示:
and so your main qml may look like this:
WorkerScript {
id: myWorker
source: "func.js"
onMessage: {
switch(messageObject.action)
{
case 'start':
spinner.running = true;
uiController.doSomething();
break;
case 'finish':
spinner.running = false;
uiController.doSomethingAnother();
break;
}
}
}
这篇关于WorkerScript对Controller类的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!