Python/GUI - Qt for Python(Pyside6)

Write your first Qt application

lifeseed 2025. 5. 23. 01:16

출처 : 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

 

오늘은 설치된 Pyside API를 이용한 첫번째 어플리케이션입니다.

 

텍스트 창과 Click me! 라는 버튼으로 구성된 간단한 어플리케이션입니다.

Click me! 버튼을 클릭할 때 마다 인사말이 다음과 같이 변경됩니다.

["Hallo Welt" -> "Hei maailma" -> "Hola Mundo" -> "Привет мир" -> "Hallo Welt" ...]

 

 

Source Code

import sys
import random
from PySide6 import QtCore, QtWidgets, QtGui

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.hello = ["Hallo Welt", "Hei maailma", "Hola Mundo", "Привет мир"]

        self.button = QtWidgets.QPushButton("Click me!")
        self.text = QtWidgets.QLabel("Hello World",
                                     alignment=QtCore.Qt.AlignCenter)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.magic)

    @QtCore.Slot()
    def magic(self):
        self.text.setText(random.choice(self.hello))

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())

 

코드 실행 순서

1. __main__  아래 구문에서 시작

app = QtWidgets.QApplication([]) : Qt Application 의 instance를 생성

 

2. QWidget를 상속받은 MyWidget Class를 생성하여 widget을 가져옴

 

3. widget.resize(800, 600) 

800 x 600 크기의 윈도우로 설정

 

4. widget.show()

widget을 보여지도록 설정

 

5. sys.exit(app.exec())

app.exec()를 통하여 QT를 실행. GUI를 종료시 sys.exit() 를 통하여 python 프로그램 종료

 

MyWidget 

1. 버튼 생성 : 버튼 이름은 Click me!

self.button = QtWidgets.QPushButton("Click me!")

 

2. 라벨 생성 : 초기 값은 Hello World

self.text = QtWidgets.QLabel("Hello World", alignment=QtCore.Qt.AlignCenter)

 

3. widget의 layout을 Vertical Box로 생성 후 Label 과 Button을 순서대로 배치
self.layout = QtWidgets.QVBoxLayout(self)

self.layout.addWidget(self.text)
self.layout.addWidget(self.button)

 

4. 버튼 클릭시 이벤트 함수 등록
self.button.clicked.connect(self.magic)

@QtCore.Slot()
def magic(self):
    self.text.setText(random.choice(self.hello))

 

 

반응형