날먹을 위한 몸부림/QT (PySide6)

python을 백앤드로 사용하는 qml 데모 - 2

프로그래밍하는 지팡이 2024. 6. 21. 17:45
import sys
from PySide6.QtCore import QObject, Slot
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine, QmlElement
QML_IMPORT_NAME = "hamster.backend"
QML_IMPORT_MAJOR_VERSION = 1
@QmlElement
class Backend(QObject):
def __init__(self):
super().__init__()
self.counter = 0
@Slot()
def button_clicked(self):
self.counter += 1
print(f"Button clicked {self.counter} times")
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load("qml/main.qml")
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec())
view raw main.py hosted with ❤ by GitHub
import QtQuick
import QtQuick.Controls
import hamster.backend 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Hello QML"
Backend {
id: backend
}
Button {
text: "Click me"
highlighted: true
anchors.centerIn: parent
onClicked: backend.button_clicked()
}
}
view raw main.qml hosted with ❤ by GitHub

 

https://boa9448.tistory.com/41

 

python을 백앤드로 사용하는 qml 데모 - 1

HTML 삽입미리보기할 수 없는 소스

boa9448.tistory.com

위와 다른 방식으로 qml에 파이썬 객체를 노출함

 

 

QML_IMPORT_NAME = "hamster.backend"
QML_IMPORT_MAJOR_VERSION = 1

위와 같이 노출할때 사용할 패키지 이름과 버전을 지정하고

 

@QmlElement
class Backend(QObject):

노출할 클래스를 QmlElement로 장식해줌

 

import hamster.backend 1.0

그리고 QML에서 포함

 

 

Backend {
    id: backend
}

Button {
    text: "Click me"
    highlighted: true
    anchors.centerIn: parent
    onClicked: backend.button_clicked()
}

그리고 노출된 객체를 사용

 

 

결과는 이전과 같음