Table of Contents
pyQt Desiger를 이용한 UI 개발
모듈라 Pi에서 Python을 사용하여 UI 프로그램을 개발하는 방법은 크게 두 가지가 있습니다.
첫 번째는 하드코딩 방식 위젯의 좌표, 크기, 레이아웃 등을 Python 코드로 직접 정의하는 방식입니다.
두 번째는 디자이너 툴(PyQt5/6, Tkinter, PySide6)을 이용한 시각적 UI 설계 방식입니다. 이 방법은 개발과 유지보수가 훨씬 수월합니다.
본 장에서는 이 중 PyQt5의 Qt Designer를 활용하여 UI를 시각적으로 설계하고, 설계한 UI를 모듈라 Pi에서 실제로 실행하는 방법을 단계별로 설명합니다.
참고자료
1. UI 디자인
Qt Designer에서는 버튼, 라벨, 입력창 등 필요한 위젯을 마우스로 드래그 앤 드롭하여 배치할 수 있습니다. 이러한 방식으로 손쉽게 레이아웃을 구성하고 UI 화면을 시각적으로 디자인합니다.
- 아래의 디자인은 lable 2개와 Botten 1개로 디자인한 예제입니다. ☞ (Sample 디자인 파일)
2. .ui파일 .py변환 하여 프로젝트 구성
Qt Designer에서 디자인을 완료한 화면은 `.ui` 확장자로 저장됩니다. `.ui` 파일은 XML 기반으로 UI 구성 정보만 포함하고 있으며, Python 코드와 직접적으로 연결되지는 않습니다. 따라서 Python 프로그램에서 UI를 사용하기 위해서는 `.ui` 파일을 Python 코드 형태로 변환해야 합니다.
1.) UI 파일 → Python 코드 파일로 변환
- 파일 변환 :
pyuic5 -o ui_main.py first_design.ui - eg. first_design.ui : Qt Designer에서 저장한 UI 파일
- eg. ui_main.py : 변환된 UI 클래스가 포함된 Python 코드 파일
2.) 프로젝트 파일 구성
- 프로젝트 폴더의 파일 구성 : first_design.ui (원본 ui파일), ui_main.py(pyuic5 변환된 UI 클래스 파일), main.py(실행 코드)
변환이 완료된 후, ui_main.py 파일을 프로젝트 main.py 파일 내에서 import하여 사용하면 됩니다.
main.py
import sys from PyQt5.QtWidgets import QApplication, QMainWindow from ui_main import Ui_Form class MainWindow(QMainWindow, Ui_Form): def __init__(self): super().__init__() self.setupUi(self) # 초기 색상 self._is_green = True self._set_lamp("green") self.Button.clicked.connect(self.toggle_lamp) def _set_lamp(self, color): # ui에서 램프 크기가 100x100 이므로 radius 50 사용 style = f"background-color: {color}; border: 1px solid #000; border-radius: 50px;" self.lamp.setStyleSheet(style) self.lamp def toggle_lamp(self): if self._is_green: self._set_lamp("yellow") self.Button.setText("OFF") else: self._set_lamp("green") self.Button.setText("ON") self._is_green = not self._is_green if __name__ == "__main__": app = QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_())
- UI 파일을 변환하지 않고 직접 로드하여 사용하기
Qt Designer에서 생성된 .ui 파일은 `pyuic5` 변환 과정 없이도 Python 실행 시점에 직접 로드하여 사용할 수 있습니다. 이 방식은 UI를 자주 수정하는 개발 환경에서 즉시 반영 가능한 장점이 있습니다.
.ui 파일과 main.py 파일이 동일한 폴더 내에 있다고 가정할 때, loadUi() 함수를 이용하여 .ui 파일을 메인 윈도우 객체에 직접 로드하고, 위젯(Button, Label 등)을 그대로 사용할 수 있습니다.
from PyQt5.uic import loadUi ui_file = Path(__file__).parent / "first_design.ui" loadUi(ui_file, self)
main.py
import sys from pathlib import Path from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.uic import loadUi class MainWindow(QMainWindow): def __init__(self): super().__init__() # main.py 와 같은 폴더에 있는 ui 파일 로드 ui_file = Path(__file__).parent / "first_design.ui" loadUi(ui_file, self) # 초기 색상 설정 self._is_green = True self._set_lamp("green") # UI에서 버튼 이름은 Qt Designer에서 설정한 객체 이름 그대로 사용 self.Button.clicked.connect(self.toggle_lamp) def _set_lamp(self, color): # 램프 크기 100x100 기준 border-radius 반지름 50 style = ( f"background-color: {color}; " f"border: 1px solid #000; " f"border-radius: 50px;" ) self.lamp.setStyleSheet(style) def toggle_lamp(self): if self._is_green: self._set_lamp("yellow") self.Button.setText("OFF") else: self._set_lamp("green") self.Button.setText("ON") self._is_green = not self._is_green if __name__ == "__main__": app = QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_())
