한국어
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 85949
119 임의의 메모리 영역(QImage)에 QPainter를 이용하여 그리기 file makersweb 2017.12.19 3445
118 QML 코딩 규칙 makersweb 2021.09.05 3247
117 qbs 사용 방법(Helloworld) file makersweb 2019.10.23 3094
116 QString 문자열에서 숫자만 추출해서 QString으로 반환 makersweb 2017.01.10 3078
115 다국어 지원 어플리케이션 개발 file makersweb 2018.01.27 2978
114 QTextCodec클래스를 사용하여 유니코드와 EUC-KR 변환 makersweb 2019.03.25 2893
113 컨테이너 클래스 - QVector makersweb 2020.03.17 2842
112 UI 폼(Form)작성 시 탭 순서(Tab Order) 설정 file makersweb 2020.08.24 2786
» QML에서 멀티 스레드(multithreading) 프로그래밍 file makersweb 2019.05.25 2657
110 Qt5기반 독립 프로세스(out-of-process)로 동작하는 가상키보드(virtual keyboard) file makersweb 2019.02.24 2628
109 구글 클라우드 Speech-To-Text API를 Qt기반(C++, Qml)테스트 [7] file makersweb 2019.01.20 2620
108 Qt3D의 QML 타입으로 3D렌더링 file makersweb 2019.11.20 2530
107 리눅스에서 Qt4.8기반 어플리케이션의 한글입력 file makersweb 2018.11.29 2437
106 QtWayland와 ivi-compositor file makersweb 2018.12.27 2403
105 [Qt News] Qt6 Git 개발 초기 단계 시작하기 j2doll 2019.08.02 2332
104 QOpenVirtualkeyboard(Qt 5용 한글 및 영문, 숫자 가상키보드) file makersweb 2019.11.27 2242
103 main함수 명령줄 옵션 해석 makersweb 2020.09.01 2232
102 Qt Creator에서 임베디드 장치로 deploy설정(Custom Process Step) file makersweb 2019.06.15 2201
101 OpenGL 렌더링을 QtQuick과 통합하는 방법 file makersweb 2019.10.01 2181
100 Qt Creator에서 Qt의존성 라이브러리 자동복사하기 file makersweb 2019.10.19 2165