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

Code Genie·2024년 11월 22일

Python 백엔드에서 QML로 데이터를 전달하여 UI를 업데이트 하는 방법에는 여러가지 있다.

정말 여러가지 방법이 있었고 여러 테스트 결과
크게 2가지로 정리 할 수 있었다.

  1. 백엔드 값을 바로 업데이트
  2. 백엔드 값을 가공하거나, 또는 백엔드 값 조건에 따라 UI를 변경하는 등의 작업을 할 경우

이번 포스트에서는 1번 방법 예제

# 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):
    valueChanged = Signal()

    def __init__(self):
        super().__init__()
        self._values = {"marginValue": "10", "propertyValue": "20"}

    @Property('QVariant', notify=valueChanged)
    def values(self):
        return self._values
        
    @values.setter #% setter을 이용한 전체 딕셔너리를 업데이트
    def values(self, new_values):
        if self._values != new_values:
            self._values = new_values  
            self.valueChanged.emit()

    @Slot(str, str) #% 개별 키 값 업데이트
    def update_value(self, key, value):
        if key in self._values and self._values[key] != value:
            self._values[key] = value
            self.valueChanged.emit()

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

    backend = Backend()

    qml_file = os.path.join(os.path.dirname(__file__), "dict.qml")
    
    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("backend", backend)
    engine.load(qml_file)
    import time
    if not engine.rootObjects():
        sys.exit(-1)
    
    def update_random_values():
        margin_value = str(random.randint(0, 100))
        property_value = str(random.randint(0, 100))
        backend.update_value("marginValue", margin_value)
        backend.update_value("propertyValue", property_value)
    
    backend.update_value("marginValue", "111")
    backend.values = {"marginValue": "50", "propertyValue": "100"}  #% setter 사용
    
    timer = QTimer()
    timer.timeout.connect(update_random_values)
    timer.start(10  
    
    sys.exit(app.exec())

  • 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: backend.values["marginValue"]
            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: backend.values["propertyValue"]
            color: "#fff"
        }
    }
    
}

Python 백엔드 => Qt 6.x QML로 데이터 전달 (2) 에서는
Connections를 이용하여 값을 가공하여 업데이트 하거나 추가 작업을 하는 방법에 대해서 알아본다

profile
1인 개발

0개의 댓글