Implementing an animated wait note in QML and showing it while running time consuming JavaScript functions
This code snippet shows how to implement a wait note with a spinning animation in QML. The snippet also shows how to run heavy JavaScript functions at the same time using a WorkerScript, and then clear the wait note when the operations complete.
Article Metadata
Tested with
Compatibility
Platform Security
Article
Contents |
Overview
QML’s NumberAnimation element and rotation property are used to create a spinning wait note without using animated GIF files. The wait note is implemented as a custom component defined in WaitNote.qml, so it can be created dynamically and destroyed when needed by using the Loader element. The main element of WaitNote.qml is MouseArea for disabling all the mouse events when the wait note is being shown. The image used in the animation is shown on the right.
Wait notes are meant to indicate that some long-running operations are being done. Usually these kinds of operations block the main GUI thread of the application and the animation cannot be played. This problem is avoided by using the WorkerScript element, which makes it possible to run JavaScript functions in a new thread.
When the JavaScript functions need to be run, the WaitNote component is loaded and a message is sent to the WorkerScript element. The WorkerScript element then runs the functions and when they are finished a message is sent back. When this message is received, the WaitNote.qml component is destroyed and the values returned by the functions are ready to be used.
Preconditions
Qt 4.7 or higher is installed.
Sources
WaitNote.qml
import QtQuick 1.0
MouseArea {
id: waitNote
anchors.fill: parent
Image {
anchors.centerIn: parent
source: "waitNote.png"
NumberAnimation on rotation {
loops: Animation.Infinite
from: 0
to: 360
duration: 1500 // Define the desired rotation speed.
}
}
}
Using of WaitNote.qml
import QtQuick 1.0
Item {
//...
/* Call this function to run the time
consuming JavaScript functions. */
function runFunctions() {
loader.source = "WaitNote.qml"
worker.sendMessage({});
}
Loader {
id: loader
anchors.fill: parent
}
WorkerScript {
id: worker
source: "script.js"
onMessage: {
loader.source = "";
// Now the returned values can be used.
console.log(messageObject.returnValue);
}
}
//...
}
scripts.js
function heavyFunction() {
/* Long-running operations and calculations
are done here. */
}
WorkerScript.onMessage = function(message) {
var retVal = heavyFunction();
WorkerScript.sendMessage({returnValue: retVal})
}
Postconditions
This code snippet demonstrated how to implement a wait note with a spinning animation in QML. The snippet also demonstrated how to play the animation and run heavy JavaScript functions at the same time.



(no comments yet)