QML WorkerScript Element
The WorkerScript element enables the use of threads in QML
source : url
Signals : onMessage
Methods : sendMessage
Detailed Description
Use WorkerScript to run operations in a new thread. This is useful for running operations in the background so that the main GUI thread is not blocked.
Messages can be passed between the new thread and the parent thread using sendMessage() and the onMessage() handler.
WorkerScript 用於產生新的線程,並通過訊息進行通訊。
qml檔案中聲明 WorkerScript { id: worker; source: "dataloader.js" } id和js檔案路徑。這樣qml中就可以通過worker.sendMessage(msg);發送訊息(msg是qml中定義的一var變數),js中總是這樣定義WorkerScript.onMessage = function(msg)函數,其中msg可以含有worker msg中的多個變數或屬性。同樣js中也可以通過WorkerScript.sendMessage({src:src,data:jresult});向qml發送訊息,其中qml中onMessage負責接收。
另外注意:
WorkerScript線程內沒有全域變數,因此下面這樣用法會在msg.model.append(string );造成線程的崩潰
var string = "Time:";
WorkerScript.onMessage = function(fmUrl) {
if (msg.action == 'appendCurrentTime') {
var data = {'time': new Date().toTimeString()};
msg.model.append(string );
msg.model.append(data);
msg.model.sync(); // updates the changes to the list
}
}