한국어
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 87850
179 Qbs 프로젝트를 정의하기 위해 사용되는 몇가지 중요한 아이템들 file makersweb 2019.10.13 370
178 Qt 6.4에 추가될 Qt Quick 3D Physics file makersweb 2022.08.07 440
177 HTTPS URL을 연결할 때 SslHandshakeFailedError 오류 makersweb 2022.07.31 467
176 Qt 응용프로그램에 Web 구성 요소를 표시 with Servo file makersweb 2024.04.27 468
175 Qt Android 앱에 AdMob 배너달기 file makersweb 2021.12.04 485
174 그래픽 소프트웨어에서 디자인 내보내기 (Exporting Designs from Graphics Software) j2doll 2020.12.25 503
173 Binding 타입으로 객체 속성 간 묶기 makersweb 2022.03.04 525
172 Qt Quick Controls 2에 네이티브 데스크탑 스타일 추가 file makersweb 2020.11.23 584
171 성능 고려 및 제안 사항 makersweb 2022.03.07 597
170 VirtualKeyboard 스타일 커스터 마이징 makersweb 2022.03.13 597
169 안드로이드용 Qt 6.2 makersweb 2021.10.02 607
168 앱을 종료할 때 QML 바인딩 오류를 피하는 방법 makersweb 2021.08.08 621
167 Qt Safe Renderer 개요 file makersweb 2022.09.08 631
166 응용프로그램 자동실행 설정 (on Windows) makersweb 2021.05.08 658
165 최초의 Qt 6.0 스냅샷 제공 (First Qt 6.0 Snapshot Available) j2doll 2020.06.21 681
164 clazy 로 13개의 시그널, 슬롯 오류 해결 makersweb 2022.08.23 691
163 Qt Marketplace 발표 makersweb 2019.12.02 692
162 QML과 코루틴(Coroutines) makersweb 2020.11.03 692
161 QProcess 보안 권고 리뷰 file makersweb 2022.09.18 695
160 Embedded Linux 에서 Qt 및 Graphics Stack file 운영자 2020.05.27 724