한국어
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 86033
79 QThread 소개 및 예제 makersweb 2019.12.25 19528
78 ApplicationWindow 와 메뉴바(MenuBar)구성 file makersweb 2020.01.04 1502
77 Qt 멀티 스레드 프로그래밍 시 유의해야 할 몇 가지 makersweb 2020.01.13 4880
76 Qt로 XML 파싱 : Qt 6에서 업데이트된 (Parsing XML with Qt: Updates for Qt 6) [1] j2doll 2020.01.16 979
75 2020년에 변경되는 Qt 오퍼 (Qt offering changes 2020) [2] j2doll 2020.01.31 721
74 QOpenGLWidget 을 투명하게 적용 file makersweb 2020.02.05 1041
73 라즈베리파이4에 대한 Qt 5.14.1 크로스컴파일 [1] file makersweb 2020.02.12 4450
72 QLabel의 텍스트 색과 배경색을 변경 makersweb 2020.02.25 6645
71 Qt로 작성된 안드로이드 APP에 Splash Screen을 추가 file makersweb 2020.03.10 885
70 컨테이너 클래스 - QVector makersweb 2020.03.17 2852
69 콘솔에서 사용자 입력받기 file makersweb 2020.03.22 51851
68 Qt 5.15 및 Qt 6의 출시 일정 makersweb 2020.04.09 934
67 재진입(Reentrancy) 및 스레드 안전성(Thread-Safety) makersweb 2020.04.19 1218
66 Qt기반의 서버와 클라이언트간 SOAP(Simple Object Access Protocol) file makersweb 2020.05.11 974
65 ShaderEffect QML Type을 이용한 버튼 클릭 효과 file makersweb 2020.05.22 1092
64 Embedded Linux 에서 Qt 및 Graphics Stack file 운영자 2020.05.27 615
63 Qt MQTT 에 대해서 file makersweb 2020.06.02 961
62 최초의 Qt 6.0 스냅샷 제공 (First Qt 6.0 Snapshot Available) j2doll 2020.06.21 592
61 Qt로 데이터를 직렬화(serialization)하는 방법 makersweb 2020.08.04 2068
60 UI 폼(Form)작성 시 탭 순서(Tab Order) 설정 file makersweb 2020.08.24 2797