한국어
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 85726
178 가상키보드(Qt Virtual Keyboard)를 사용하는 방법 [32] file makersweb 2019.05.03 220762
177 콘솔에서 사용자 입력받기 file makersweb 2020.03.22 51837
176 QString 문자열 다루기 예제 운영자 2019.01.26 39939
175 Windows에서 Qt 설치 따라하기 file makersweb 2019.10.14 30848
174 Qt의 시그널 슬롯 시스템 file makersweb 2015.10.20 23538
173 QThread 소개 및 예제 makersweb 2019.12.25 19388
172 QtCreator Design으로 GUI만들기 (QML로 만드는 Hello World -2) [1] file makersweb 2019.05.26 14837
171 초보자를 위한 첫번째 프로젝트 - QML로 만드는 Hello World file makersweb 2018.03.16 14426
170 Qt 프로그래밍의 시작 makersweb 2015.10.25 14359
169 Qml과 C++로 구현하는 GUI어플리케이션 file makersweb 2018.12.25 13904
168 QML과 QtQuick 모듈 개념과 기본 타입들 makersweb 2019.04.26 13374
167 Windows에서 라즈베리파이3용 Qt5.10.0 크로스컴파일 [20] file makersweb 2018.02.23 12864
166 Qt의 오픈소스 라이센스 소개 file makersweb 2019.12.15 12522
165 Qml 기본 컴포넌트 강좌 (1) file makersweb 2019.01.03 12046
164 QtSerialPort를 사용한 시리얼(Serial)통신 [3] makersweb 2019.05.21 11864
163 Qt Installer Framework - 패키징, 설치프로그램 제작 file makersweb 2018.10.14 11644
162 Qt 응용프로그램 배포(windows) file makersweb 2018.10.10 11289
161 Ubuntu Linux에서 Qt Creator 설치 file makersweb 2016.03.06 10665
160 Qt의 스레드간 시그널 슬롯의 커넥션타입 [1] makersweb 2015.10.24 10151
159 QML 강좌 - 동적 Listing (ListView) file makersweb 2019.06.01 10074