Designer를 이용해서 작업할 때, Slot 단위의 추가가 아니라, 새로운 UI 클래스를 적용해야 할 때가 있습니다.
예를 들어 "게임 화면용 Widget"을 추가하려고 할 때, 해당 Widget은 굉장히 복잡한 Paint, Mouse, Keyboard 등의 이벤트를 처리해야 합니다. 그래서 이 때는 "게임 화면용 Widget"을 미리 Python 코드로 만들어 놓고 Designer에서 그 클래스로 대체해 주는게 더 낫습니다.
Custom Widget 정의
그래픽 처리만 담당하는 Widget을 아래처럼 gamewiget.py 파일에 정의합니다.
from PySide6.QtCore import * # type: ignore from PySide6.QtGui import * # type: ignore from PySide6.QtWidgets import * # type: ignore # 게임용 위젯 class GameWidget(QWidget): def __init__(self, parent= None): super().__init__(parent) self.initUI() def initUI(self): self.setGeometry(10, 10, 100,100) self.show() def paintEvent(self, e): qp = QPainter() qp.begin(self) qp.drawRect(10, 10, 10, 10) qp.end()
Designer에서 Widget 추가하기
Designer에서 해당 Widget을 GameWidget으로 변경하기
Widget을 우클릭하여 다음으로 승격을 선택
클래스 이름에는 앞에서 만들었던 이름인 GameWidget, 헤더파일에는 gmaewidget.h 입력
추가 버튼 누르고, 승격 버튼 누름
모든 작업들이 완료되면, 우측 "객체 탐색기" 부분에 Widget이 GameWidget으로 변경된 것을 확인할 수 있습니다.
Python Code 복사하여 Python IDE로 붙여넣기 수행
Pyside QT Designer로 버튼 만들기에서 수행한 작업과 동일하게 진행합니다.
작업이 완료되면 자동으로 from gamewidget import GameWidget 구문이 삽입된 것을 알 수 있습니다.
그리고 setupUi 함수에서 widget이 self.widget = GameWidget(Form) 으로 변경된것도 확인 가능합니다.
from PySide6.QtCore import * # type: ignore from PySide6.QtGui import * # type: ignore from PySide6.QtWidgets import * # type: ignore from gamewidget import GameWidget class Ui_Form(object): def setupUi(self, Form): if not Form.objectName(): Form.setObjectName(u"Form") Form.resize(400, 300) self.widget = GameWidget(Form) self.widget.setObjectName(u"widget") self.widget.setGeometry(QRect(20, 10, 361, 231)) self.widget.setAutoFillBackground(True) self.pushButton = QPushButton(Form) self.pushButton.setObjectName(u"pushButton") self.pushButton.setGeometry(QRect(20, 260, 351, 24)) self.retranslateUi(Form) QMetaObject.connectSlotsByName(Form) # setupUi def retranslateUi(self, Form): Form.setWindowTitle(QCoreApplication.translate("Form", u"Form", None)) self.pushButton.setText(QCoreApplication.translate("Form", u"PushButton", None)) # retranslateUi # UI 디자이너에서 가져온 UI를 연결하는 클래스 class WindowClass(QMainWindow, Ui_Form): def __init__(self): super().__init__() self.setupUi(self) # Main 함수 if __name__ == '__main__': app = QApplication() window = WindowClass() window.show() app.exec()
실행 확인
코드를 실행하면 GameWidget의 paint 이벤트에서 정의한 qp.drawRect(10, 10, 10, 10) 함수가 잘 작동하는 것을 확인할 수 있습니다(너무 작게 그려서 잘 안보이는거 같네요 ㅠㅠㅠ).
이상입니다.
더 다양한 정보는 Pyside Qt 강좌에서 확인해 보세요.





댓글 없음:
댓글 쓰기