Python/GUI - Qt for Python(Pyside6)

First QML Application with Pyside6

lifeseed 2025. 5. 23. 01:37

출처 : https://doc.qt.io/qtforpython-6/gettingstarted.html#getting-started

 

Getting Started - Qt for Python

What is Qt Qt, QML, Widgets… What is the difference?

doc.qt.io

 

 

QT Application 중 QML을 이용한 첫번째 예제입니다.

 

1. QML 작성

Example 폴더를 생성하여 Main.qml 이라는 파일로 QML Language file을 생성합니다.

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Window {
    width: 300
    height: 200
    visible: true
    title: "Hello World"

    readonly property list<string> texts: ["Hallo Welt", "Hei maailma",
                                           "Hola Mundo", "Привет мир"]

    function setText() {
        var i = Math.round(Math.random() * 3)
        text.text = texts[i]
    }

    ColumnLayout {
        anchors.fill:  parent

        Text {
            id: text
            text: "Hello World"
            Layout.alignment: Qt.AlignHCenter
        }
        Button {
            text: "Click me"
            Layout.alignment: Qt.AlignHCenter
            onClicked:  setText()
        }
    }
}

 

앞서 구현한 MyWidget 부분을 QML로 작성된 것입니다.

 

2. qmldir 파일 생성

Example 폴더에 Main.qml과 함께 위치 하며, QML 모듈을 설명하기 위한 파일

module Example
Main 254.0 Main.qml

 

 

3. 구동 코드 작성

hello_qt_gui.py 라는 이름으로 python 코드 작성

import sys
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine

app = QGuiApplication.instance()
if app is None:
    app = QGuiApplication(sys.argv)

engine = QQmlApplicationEngine()
engine.addImportPath(sys.path[0])
engine.loadFromModule("Example", "Main")
if not engine.rootObjects():
    sys.exit(-1)
    
exit_code = app.exec()
print("Exit code:", exit_code)
del engine

sys.exit(exit_code)

 

 

 

 

실행영상

 

 

반응형