한국어
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 86884
179 Qt 응용프로그램에 Web 구성 요소를 표시 with Servo file makersweb 2024.04.27 298
178 Qbs 프로젝트를 정의하기 위해 사용되는 몇가지 중요한 아이템들 file makersweb 2019.10.13 330
177 Qt 6.4에 추가될 Qt Quick 3D Physics file makersweb 2022.08.07 393
176 HTTPS URL을 연결할 때 SslHandshakeFailedError 오류 makersweb 2022.07.31 411
175 Qt Android 앱에 AdMob 배너달기 file makersweb 2021.12.04 433
174 그래픽 소프트웨어에서 디자인 내보내기 (Exporting Designs from Graphics Software) j2doll 2020.12.25 439
173 Binding 타입으로 객체 속성 간 묶기 makersweb 2022.03.04 471
172 Qt Quick Controls 2에 네이티브 데스크탑 스타일 추가 file makersweb 2020.11.23 527
171 Qt Creator 에서 GitHub Copilot 사용하기 file makersweb 2024.04.13 536
170 VirtualKeyboard 스타일 커스터 마이징 makersweb 2022.03.13 537
169 앱을 종료할 때 QML 바인딩 오류를 피하는 방법 makersweb 2021.08.08 547
168 안드로이드용 Qt 6.2 makersweb 2021.10.02 555
167 성능 고려 및 제안 사항 makersweb 2022.03.07 564
166 Base64로 인코딩된 파일을 복원 makersweb 2023.08.06 574
165 QtQuick 애플리케이션에 Rive 애니메이션 통합 makersweb 2024.03.31 597
164 Qt Safe Renderer 개요 file makersweb 2022.09.08 598
163 응용프로그램 자동실행 설정 (on Windows) makersweb 2021.05.08 610
162 QML과 코루틴(Coroutines) makersweb 2020.11.03 625
161 하드디스크 드라이브 여유 공간 계산 file makersweb 2023.01.15 630
160 clazy 로 13개의 시그널, 슬롯 오류 해결 makersweb 2022.08.23 641