WorkerScript QML Type

官方描述:在一个Qt Quick应用程序中可以使用线程了.

Import Statement:     import QtQuick .
属性:
source : url
信号:
message(jsobject msg)

 

使用WorkerScript在一个新线程中执行操作.再后台执行操作是很有用的,主GUI线程也不会锁定.

Message可以在新线程和父线程之间通过sendMessage()和onMessage()进行传递消息.
方法:
sendMessage(jsobject message)
案例:

功能是:鼠标点击窗口中的某一个位置,程序中的那行文本便会更新当前鼠标的XY坐标.

运行效果如下图所示:

import QtQuick 2.0

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:

上面的worker script指定了一个javascript文件,"script.js",在这个新线程中处理将被执行的操作.下面就是这个script.js文件

WorkerScript.onMessage = function(message) {
    // ... long-running operations and calculations are done here
    WorkerScript.sendMessage({ 'reply': 'Mouse is at ' + message.x + ',' + message.y })
}
当用户在矩形中点击任意位置时,sendMessage()被唤醒,触发了workerScript.onMessage()再script.js中进行处理.这个返回一个回复消息,并且在之后被myWorker的onMessage()句柄接收到.
 
限制:
因为WorkerScript.onMessage()函数是在分开的线程中执行的,所以JavaScript文件从主QML工程中分开的上下文中被评估.这意味着不像常规的导入到QML中的javascript文件那样,上例中的script.js不能存取属性,方法或者其他的qml对象的属性,它也不能通过QQmlContext设置QML对象的任何上下文属性.
另外,在值类型上也有限制.可以发送到或者接受来自workerscript的值.具体见sendMessage()细节.
 

Worker script不能使用.导入语法:
见 Qt Quick Examples - Threading and Threaded ListModel Example.

 

属性文档:
source : url
这里保存着javascript文件的地址url,里面实现了WorkerScript.onMessage()处理线程操作.

信号文档:
message(jsobject msg)
This signal is emitted when a message msg is received from a worker script in another thread through a call to sendMessage().
通信句柄是onMessage.

方法文档:
sendMessage(jsobject message)
在其他线程中发送给定的消息到script 句柄.其他的worker script句柄可以接收消息,通过onMessage().
消息对象只可以包含一下的值类型:
boolean, number, string
JavaScript objects and arrays
ListModel objects (任何其他类型的 QObject* 是不被允许的.)

所有的对象和数组都被拷贝到message上.除了ListModel对象,在消息中任何被其他线程修改了的发送出来的信息 将不会再原始对象上反映出来.

转载于:https://www.cnblogs.com/L-Arikes/p/4380382.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值