Python 백엔드 => Qt 6.x QML로 데이터 전달 (2)

Code Genie·2024년 11월 22일

Python 백엔드 => Qt 6.x QML로 데이터 전달 (1) 에 이어
이번에는 Connections를 이용하여 UI 업데이트

# main.py
import sys, os
from PySide6.QtCore import QObject, Property, Signal, Slot, QTimer
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine


class Backend(QObject):
    nameChanged = Signal(str)  # 문자열을 전달하는 Signal
    
    #% QML에서의 Signal-Handler 패턴
        #$ on<SignalName> 함수
        #$ QML에서 Python 백엔드가 Signal을 emit하면, 해당 Signal과 같은 이름의 핸들러가 자동으로 호출됩니다.
        #$ 함수 이름은 on<SignalName> 형태를 따라야 하며, Signal 이름과 정확히 매칭되어야 합니다.
        #$ QML에서는 onNameChanged라는 이름의 핸들러가 Signal에 자동 연결됩니다.
    
    def __init__(self):
        super().__init__()
    
    @Slot(str)
    def update_name(self, text):
        self.nameChanged.emit(text)

if __name__ == "__main__":
    import random
    app = QGuiApplication(sys.argv)

    backend = Backend()

    qml_file = os.path.join(os.path.dirname(__file__), "신호함수매핑방식.qml")
    
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("backend", backend)
    engine.load(qml_file)
    import time
    if not engine.rootObjects():
        sys.exit(-1)
    
    
    timer = QTimer()
    timer.timeout.connect(lambda: backend.update_name("asdf"))
    timer.start(500)  # 1000ms = 1초
    
    sys.exit(app.exec())

  • QML파일
# 신호함수매핑방식.qml

import QtQuick 6.5
import QtQuick.Controls 2.15

Window {
    visible: true
    width: 640
    height: 480
    title: "Rectangle Example"

    Rectangle {
        id: marginValue
        x: 50
        y: 50
        width: 50
        height: 30
        color: "#d9ff00"
        radius: 4

        Label {
            id: marginLabel
            anchors.centerIn: parent
            font.pointSize: 11
            font.family: "Source Code Pro SemiBold"
            text: "20"
            
            color: "#000"
        }
    }

    Rectangle {
        id: propertyValue
        x: 200
        y: 50
        width: 50
        height: 30
        color: "red"
        radius: 4

        Label {
            id: propertyLabel
            anchors.centerIn: parent
            font.pointSize: 11
            font.family: "Source Code Pro SemiBold"
            text: "10"
            color: "#fff"
        }
    }
    Connections {
        target: backend
        function onNameChanged(stringText) {
                console.log(stringText)
                propertyLabel.text = stringText
        }
    }
}
profile
1인 개발

0개의 댓글