• 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 {
         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对象,在消息中任何被其他线程修改了的发送出来的信息 将不会再原始对象上反映出来.

    生活的残酷,让我们习惯了忘记疲倦,一直奔向远方,追寻着自己的梦想。
  • 相关阅读:
    Unity3D性能优化--- 收集整理的一堆
    Unity5.3官方VR教程重磅登场-系列7 优化VR体验
    VR沉浸体验的要求
    Unity5中叹为观止的实时GI效果
    浅谈控制反转与依赖注入[转]
    unity 使用unityaction 需要注意的问题[转]
    c# orm框架 sqlsugar
    unity Instantiate设置父级物体bug
    宝塔面板 使用mongodb注意事项
    unity中gameObject.SetActive()方法的注意事项。
  • 原文地址:https://www.cnblogs.com/L-Arikes/p/4380382.html
Copyright © 2020-2023  润新知