码迷,mamicode.com
首页 > 其他好文 > 详细

在QML应用中实现threading多任务

时间:2017-04-13 21:29:35      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:time   它的   his   接受   https   object   auto   .net   tle   

在这个样例中,我们将介绍怎样在QML应用中使用QML语言提供的threading功能,实现多任务。

很多其它的阅读在:http://doc.qt.io/qt-5/qtquick-threading-example.html


我们使用Ubuntu SDK来创建以个最主要的QML项目:


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"

    /*
     This property 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(60)
    height: units.gu(85)

    Page {
        title: i18n.tr("threading")

        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);
                }
            }
        }
    }
}


在这里,我们使用了一个ListView来显示从worker thread发送来的信息(通过更新model)。这里:

  WorkerScript {
                id: worker
                source: "dataloader.js"
            }

WorkerScript定义了一个worker thread。它的运行代码在dataloader.js中:

dataloader.js


// ![0]
WorkerScript.onMessage = function(msg) {
    if (msg.action == ‘appendCurrentTime‘) {
        var data = {‘time‘: new Date().toTimeString()};
        msg.model.append(data);
        msg.model.sync();   // updates the changes to the list
    }
}
// ![0]

在Main.qml中,我们定义了一个Timer,每2秒发送一个请求给worker thread。

它的參数是一个例如以下定义的object:


{‘action‘: ‘appendCurrentTime‘, ‘model‘: listModel};

在work thread接受到发送来的信息后。在上面的代码中。检查msg中的action。并同一时候更新传入的model。

执行我们的例程:

技术分享


整个项目的源代码在:https://github.com/liu-xiao-guo/threading

在QML应用中实现threading多任务

标签:time   它的   his   接受   https   object   auto   .net   tle   

原文地址:http://www.cnblogs.com/yutingliuyl/p/6705699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!