본문 바로가기

PYTHON

[PySide6] 파이썬 UI 프로그램 시작하기(2)

반응형

2022.01.21 - [PYTHON] - [PySide6] 파이썬 UI 프로그램 시작하기(1)

 

파이썬으로 GUI를 만들기 위한 방법은 크게 2가지가 있는 것 같습니다.

1. 소스코드에서 타이핑,

2. Qt 디자이너 사용.

다른 언어를 사용할 때 보통 디자이너를 사용했기 때문에, 일일이 코드를 타이핑해서 만드는게 너무 낯섭니다.

그래서 Qt 디자이너를 사용해서 간단히 어떤식으로 구성되는지 살펴 보았습니다.

목표는 버튼을 클릭하면 메시지 박스가 출력되는 것입니다.

 

 

Qt 디자이너를 실행하고 버튼을 추가한 후 test.ui로 저장합니다.

 

그리고 test.ui를 어떻게 사용할지 선택을 해야합니다.

1. test.ui를 파이썬 코드로 변환한 후 사용.

2. test.ui를 그대로 사용.

1번의 경우, 디자인이 변경될 때 마다 코드 변환 작업을 해야하므로 매우 번거로울 것 같습니다.

그래서, 2번의 방법을 선택했습니다.

Qt 공식 문서에 있는 코드에서 ui파일 불러오는 부분만 수정했습니다.

 

import sys
import os
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtCore import QFile, QIODevice


if __name__ == "__main__":
    app = QApplication(sys.argv)

    dir_path = os.path.dirname(os.path.realpath(__file__))
    ui_file_name = os.path.join(dir_path, "test.ui")
    ui_file = QFile(ui_file_name)

    if not ui_file.open(QIODevice.ReadOnly):
        print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
        sys.exit(-1)

    loader = QUiLoader()
    window = loader.load(ui_file)
    ui_file.close()

    if not window:
        print(loader.errorString())
        sys.exit(-1)

    window.show()

    sys.exit(app.exec())

 

실행하면 다음과 같이 윈도우가 출력됩니다.

 

 

이번에는 버튼 클릭 이벤트를 추가해 보겠습니다.

다음과 같이 클래스를 하나 추가하고, 버튼 클릭에 대한 코드를 작성합니다.

 

 

 

class MainWindow:
    def __init__(self, window):
        self.window = window
        self.window.pushButton.clicked.connect(self.button_click)

    def button_click(self):
        button = QMessageBox.question(self.window, "HELLO", "Push Button.")

        if button == QMessageBox.Yes:
            QMessageBox.information(self.window, "HELLO", "Yes!")
        else:
            QMessageBox.information(self.window, "HELLO", "No!")

    def show(self):
        self.window.show()

 

그리고 MainWindow 클래스를 사용하도록 코드를 수정합니다.

 

if __name__ == "__main__":
    app = QApplication(sys.argv)

    dir_path = os.path.dirname(os.path.realpath(__file__))
    ui_file_name = os.path.join(dir_path, "test.ui")
    ui_file = QFile(ui_file_name)

    if not ui_file.open(QIODevice.ReadOnly):
        print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
        sys.exit(-1)

    loader = QUiLoader()
    window = loader.load(ui_file)
    ui_file.close()

    if not window:
        print(loader.errorString())
        sys.exit(-1)

    main_window = MainWindow(window)
    main_window.show()

    sys.exit(app.exec())

 

자 이제 실행해 보겠습니다.

 

 

음... 잘 되는군요 ㅎ 그런데, 아직 파이썬에 익숙하지 않아서 뭔가 어색하고 이상합니다. ^^

전체 소스코드입니다.

 

import sys
import os
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtCore import QFile, QIODevice


class MainWindow:
    def __init__(self, window):
        self.window = window
        self.window.pushButton.clicked.connect(self.button_click)

    def button_click(self):
        button = QMessageBox.question(self.window, "HELLO", "Push Button.")

        if button == QMessageBox.Yes:
            QMessageBox.information(self.window, "HELLO", "Yes!")
        else:
            QMessageBox.information(self.window, "HELLO", "No!")

    def show(self):
        self.window.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)

    dir_path = os.path.dirname(os.path.realpath(__file__))
    ui_file_name = os.path.join(dir_path, "test.ui")
    ui_file = QFile(ui_file_name)

    if not ui_file.open(QIODevice.ReadOnly):
        print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
        sys.exit(-1)

    loader = QUiLoader()
    window = loader.load(ui_file)
    ui_file.close()

    if not window:
        print(loader.errorString())
        sys.exit(-1)

    main_window = MainWindow(window)
    main_window.show()

    sys.exit(app.exec())

 

이제 파이썬으로 GUI 프로그램을 만들 기본기는 된 것 같으니, 아파트 매매가격지수 크롤링 프로그램 마무리 해야겠습니다. ^^

반응형