Qt Reference Documentation

QML WorkerScript Element

The WorkerScript element enables the use of threads in QML. More...

  • List of all members, including inherited members
  • Properties

    Signals

    Methods

    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.

    An example:

     import Qt 4.7
    
     Rectangle {
         width: 300; height: 300
    
         Text {
             id: myText
             text: 'Click anywhere'
         }
    
         WorkerScript {
             id: myWorker
             source: "script.js"
    
             onMessage: myText.text = messageObject.reply
         }
    
         MouseArea {
             anchors.fill: parent
             onClicked: myWorker.sendMessage({ 'x': mouse.x, 'y': mouse.y })
         }
     }

    The above worker script specifies a javascript file, "script.js", that handles the operations to be performed in the new thread. Here is script.js:

     WorkerScript.onMessage = function(message) {
         // ... long-running operations and calculations are done here
         WorkerScript.sendMessage({ 'reply': 'Mouse is at ' + message.x + ',' + message.y })
     }

    When the user clicks anywhere within the rectangle, sendMessage() is called, triggering the WorkerScript.onMessage() handler in script.js. This in turn sends a reply message that is then received by the onMessage() handler of myWorker.

    See also WorkerScript example and Threaded ListModel example.

    Property Documentation

    source : url

    This holds the url of the JavaScript file that implements the WorkerScript.onMessage() handler for threaded operations.


    Signal Documentation

    WorkerScript::onMessage ( jsobject msg )

    This handler is called when a message msg is received from a worker script in another thread through a call to sendMessage().


    Method Documentation

    WorkerScript::sendMessage ( jsobject message )

    Sends the given message to a worker script handler in another thread. The other worker script handler can receive this message through the onMessage() handler.


    X

    Thank you for giving your feedback.

    Make sure it is related to this specific page. For more general bugs and requests, please use the Qt Bug Tracker.