한국어
Qt
 

QML에서 WorkerScript를 사용하면 JavaScript 코드를 GUI 스레드와 병렬로 실행할 수 있다.

각 WorkerScript 인스턴스에는 하나의 .js 스크립트가 첨부 되고 WorkerScript.sendMessage()가 호출되면 스크립트는 별도의 스레드(별도의 QML 컨텍스트)에서 실행된다.

 

아래 예제는 일반 함수호출을 통해 카운팅을 하는 경우와 멀티 스레드로 하는 경우를 설명한다.

jwplayer

 

main.qml

import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Controls 1.4


Window {
    id: idWindow
    visible: true
    width: 320
    height: 240
    title: qsTr("Makersweb.net")

    Column{
        spacing: 5
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top
        anchors.topMargin: 40

        AnimatedImage{
            id: loading
            source: "spinner.gif"
            playing: true
            anchors.horizontalCenter: parent.horizontalCenter
        }

        Text {
            id: text
            text: qsTr("text")
            horizontalAlignment : Text.AlignHCenter
            anchors.horizontalCenter: parent.horizontalCenter
        }
    }

    Column{
        anchors.centerIn: parent
        spacing: 15

        CheckBox{
            id: async
            anchors.horizontalCenter: parent.horizontalCenter
            text: "threading"
        }
        Row{

            Button{
                text: "start"
                onClicked: {
                    if(async.checked)
                        myWorker.sendMessage({'count': 5})
                    else
                        count({'count': 5})
                }
            }
            Button{
                text: "exit"
                onClicked: {
                    Qt.quit()
                }
            }
        }
    }

    WorkerScript {
        id: myWorker
        source: "workerscript.mjs"

        onMessage: {
            text.text = messageObject.reply
        }
    }

    function count(message) {
        var count = 0
        var seconds

        for(;;){
            var current = new Date();

            if(seconds !== current.getSeconds()){
                seconds = current.getSeconds()
                count += 1
                console.log(count)
                text.text = count

                if(count === message.count)
                    break;
            }
        }
    }
}

 

체크박스를 선택하고 start 버튼을 클릭하면 WorkerScript의  sendMessage()를 호출하고 WorkerScript 인스턴스는 첨부된 "workerscript.mjs" 스크립트를 실행한다. 주의 할 점은 sendMessage()를 호출할 때 메시지 객체는 boolean, number, string, arrays, ListModel 객체의 타입만 포함 시킬수 있다.

 

workerscript.mjs

WorkerScript.onMessage = function(message) {
    // ... long-running operations and calculations are done here

    var count = 0
    var seconds

    for(;;){
        var current = new Date();

        if(seconds !== current.getSeconds()){
            seconds = current.getSeconds()
            count += 1
            console.log(count)
            WorkerScript.sendMessage({ 'reply': count })

            if(count === message.count)
                break;
        }
    }
}

 

카운팅을 하는 로직은 완전히 같지만 workerscript.mjs 스크립트를 다른 스레드에서 실행하므로 GUI가 블락되지 않음을 알 수 있다.

 

참고 페이지 : 

https://doc.qt.io/qt-5/qml-workerscript.html

https://doc.qt.io/qt-5/threads-technologies.html

번호 제목 글쓴이 날짜 조회 수
공지 Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서 운영자 2019.01.05 85849
98 Qt Marketplace 발표 makersweb 2019.12.02 617
97 QScopedPointer 소개 및 사용법 makersweb 2019.11.29 1024
96 QOpenVirtualkeyboard(Qt 5용 한글 및 영문, 숫자 가상키보드) file makersweb 2019.11.27 2240
95 Qt3D의 QML 타입으로 3D렌더링 file makersweb 2019.11.20 2520
94 라즈베리파이3에서 Boot to Qt 실행해보기 makersweb 2019.11.13 1664
93 Qt애플리케이션 객체(QCoreApplication, QGuiApplication, QApplication) 에 대해서 makersweb 2019.11.11 10086
92 Qt Quick 3D 소개 makersweb 2019.11.09 1443
91 QPushButton 의 커스텀 이미지버튼 file makersweb 2019.11.05 6384
90 qbs 사용 방법(Helloworld) file makersweb 2019.10.23 3094
89 웹기반 Qt Design Viewer [2] file makersweb 2019.10.23 1297
88 Qt Creator에서 Qt의존성 라이브러리 자동복사하기 file makersweb 2019.10.19 2162
87 Qt for Embedded Linux 화면출력 makersweb 2019.10.17 1598
86 Windows에서 Qt 설치 따라하기 file makersweb 2019.10.14 30870
85 Qbs 프로젝트를 정의하기 위해 사용되는 몇가지 중요한 아이템들 file makersweb 2019.10.13 296
84 많은 리소스를 사용하는 Qt프로젝트에서 고려해봐야 할 qmake 옵션 makersweb 2019.10.11 1236
83 Qbs에 대한 소개와 설치하는 방법 makersweb 2019.10.09 1368
82 OpenGL 렌더링을 QtQuick과 통합하는 방법 file makersweb 2019.10.01 2181
81 QML내에서의 시그널, 슬롯 시스템 makersweb 2019.09.29 6936
80 컨테이너에 적재된 객체를 편리하게 삭제하기 makersweb 2019.09.18 1662
79 C++로 구현된 모델을 QML의 ListView에서 참조 file makersweb 2019.09.07 4915