https://doc.qt.io/qtforpython-6/index.html 사이트의 Tutorial에 대한 내용을 정리입니다.
Tutorials 를 클릭하여 확인할 수 있습니다.
https://doc.qt.io/qtforpython-6/tutorials/index.html
이번 예제를 통해서 배울 수 있는 것은 다음과 같습니다.
1. QDialog를 구성하는 코드들을 Class화 한다.
2. QVBoxLayout을 이용한 Widget의 배치
3. 버튼을 연결하는 함수를 만들어서 실행
여기서 2,3번은 이미 앞선 예제에서 다루었던 부분이며, Class 로 구성하는 부분이 추가되었습니다.
1. 실행 결과 화면
해당 과제를 진행하고 나면, 입력창과 버튼이 새로로 나열된 다이얼로그 화면이 실행된다.
버튼을 클릭하면 "Hello 입력창내용"을 콘솔창에 출력한다.
2. Class 구성
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setWindowTitle("My Form")
# Create widgets
self.edit = QLineEdit("Write my name here..")
self.button = QPushButton("Show Greetings")
# Create layout and add widgets
layout = QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
# Add button signal to greetings slot
self.button.clicked.connect(self.greetings)
# Greets the user
def greetings(self):
print(f"Hello {self.edit.text()}")
클래스의 구성은 클래스 선언, 위젯 생성 및 배치, 동작 함수 정의 및 연결 로 구성할 수 있다.
1) class Form(QDialog)
- 클래스 선언 : 여기서는 QDialog를 상속받는다. (QWidget등 다른 Class를 상속받아도 된다.)
2) Widget 생성
QLineEdit, QPushButton등을 이용하여 Widget을 생성함
3) layout = QVBoxLayout(self)
- Dialog의 Main Layout으로 QVBoxLayout을 선언하여 세로 배치형태로 구성함.
- layout.addWidget() 함수를 이용하여 생성된 Widget을 배치
4) 버튼 연결함수 생성 및 연결
3. QT 실행
Pyside를 이용한 QT 실행 순서는 다음과 같다.
app = QApplication(sys.argv)
form = Form()
form.show()
QApplication을 이용한 객체 생성
QT Class 생성
Show 및 Exec
이 패턴은 늘 동일 할 것이다.
4. 전체 코드
import sys
from PySide6.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton, QVBoxLayout
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setWindowTitle("My Form")
# Create widgets
self.edit = QLineEdit("Write my name here..")
self.button = QPushButton("Show Greetings")
# Create layout and add widgets
layout = QVBoxLayout(self)
layout.addWidget(self.edit)
layout.addWidget(self.button)
# Add button signal to greetings slot
self.button.clicked.connect(self.greetings)
# Greets the user
def greetings(self):
print(f"Hello {self.edit.text()}")
if __name__ == '__main__':
# Create the Qt Application
app = QApplication(sys.argv)
# Create and show the form
form = Form()
form.show()
# Run the main Qt loop
sys.exit(app.exec())