In this example, we will show you how to use the threading functionality provided by the QML language in the QML application for multitasking. Read more in: http://doc.qt.io/qt-5/qtquick-threading-example.html
We use the Ubuntu SDK to create a basic QML project:
MAIN.QML
Import QtQuick 2.0 Import ubuntu.components 1.1/*!
\brief MainView with a Label and Button elements. */MainView {//ObjectName for functional testing purposes (AUTOPILOT-QT5) ObjectName: "MainView"//note! ApplicationName needs to match the "name" field of the click Manifest ApplicationName: "Threading.liu-xiao-guo"/ * The enables the application to change orientation when the device is rotated.
The default is False.
*///automaticorientation:true//Removes the old toolbar and enables new features of the new header. Usedeprecatedtoolbar:false width:units.gu (height:units.gu) page {title:i18n.tr ("Threadin
G ") ListView {anchors.fill:parent Model:listmodel delegate:component {
Text {Text:time}} listmodel {Id:listmodel} workerscript { Id:worker SouRCE: "Dataloader.js"} Timer {Id:timer interval:2000; repeat:
True Running:true triggeredonstart:true ontriggered: {
var msg = {' Action ': ' Appendcurrenttime ', ' model ': Listmodel};
Worker.sendmessage (msg);
}
}
}
}
}
Here, we use a ListView to display the information sent from the worker thread (by updating the model). Over here:
Workerscript {
id:worker
Source: "Dataloader.js"
}
Workerscript defines a worker thread. Its execution code is in Dataloader.js:
Dataloader.js
// ! [0]
Workerscript.onmessage = function (msg) {
if (msg.action = = ' Appendcurrenttime ') {
var data = {' time ': New Date (). t Otimestring ()};
Msg.model.append (data);
Msg.model.sync (); Updates the changes to the list
}
}
//![ 0]
In Main.qml, we define a timer that sends a request to the worker thread every 2 seconds. Its parameters are an object defined as follows:
{' Action ': ' Appendcurrenttime ', ' model ': Listmodel};
After the work thread receives the sent message, in the above code, check the action in the MSG and update the incoming model at the same time.
To run our routines:
The source code of the whole project is: https://github.com/liu-xiao-guo/threading