Qt for Python 애플리케이션에서 디자이너 UI 파일 사용
양식을 파이썬 코드로 변환하기
데모를 위해 Qt Widgets 애니메이션 완화 예제를 사용합니다.
이 애플리케이션은 소스 파일 easing.py
, UI 파일 form.ui
, 리소스 파일 easing.qrc
, 프로젝트 파일 easing.pyproject
파일로 구성되어 있으며, YAML 형식으로 되어 있습니다:
{ "files": ["easing.qrc", "ui_form.py", "easing.py", "easing_rc.py", "form.ui"] }
UI 파일은 User Interface Compiler (uic)를 사용하여 양식을 작성하는 Python 코드로 변환됩니다:
uic -g python form.ui > ui_form.py
최상위 위젯의 이름이 Form
이므로 Ui_Form
이라는 Python 클래스가 생성됩니다. 이 클래스는 위젯을 매개변수로 받는 setupUi()
함수를 제공하며, 이 함수는 UI 요소를 생성하기 위해 호출됩니다:
from ui_form import Ui_Form ... class Window(QtWidgets.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.m_ui = Ui_Form() self.m_ui.setupUi(self)
나중에 위젯은 Ui_Form
클래스를 통해 액세스할 수 있습니다:
self.m_ui.graphicsView.setScene(self.m_scene)
setupUi()
외에도 Ui_Form
은 애플리케이션 언어의 변경을 나타내는 QEvent.LanguageChange 유형의 QEvent 에 대한 반응으로 호출할 수 있는 또 다른 메서드 retranslateUi()
를 제공합니다.
UiTools 접근 방식
QUiLoader 클래스는 런타임에 사용자 인터페이스를 구성하기 위한 폼 로더 객체를 제공합니다. 이 사용자 인터페이스는 QIODevice, 예를 들어 QFile 객체에서 검색할 수 있습니다. QUiLoader::load () 함수는 파일에 포함된 사용자 인터페이스 설명을 사용하여 양식 위젯을 구성합니다.
이 함수는 uiloader 예제에 나와 있습니다:
from PySide2.QtUiTools import QUiLoader if __name__ == '__main__': # Some code to obtain the form file name, ui_file_name app = QApplication(sys.argv) ui_file = QFile(ui_file_name) if not ui_file.open(QIODevice.ReadOnly): print("Cannot open {}: {}".format(ui_file_name, ui_file.errorString())) sys.exit(-1) loader = QUiLoader() widget = loader.load(ui_file, None) ui_file.close() if not widget: print(loader.errorString()) sys.exit(-1) widget.show() sys.exit(app.exec_())
리소스 가져오기
단일 디렉토리 사용
리소스 파일에서 아이콘을 사용할 때 resources.qrc
, uic
은 양식 가져오기를 생성합니다:
import resources_rc
이는 Resource Compiler (rcc ) 도구를 호출( -g python
명령줄 옵션 전달)하여 생성된 resources_rc.py
파일이 양식 소스와 동일한 디렉터리에 존재한다고 가정합니다.
uic
에 --rc-prefix
명령줄 옵션이 있으면 rc
표시기가 앞에 붙게 됩니다:
import rc_resources
--from-imports
명령줄 옵션을 사용하면 '.'를 기준으로 가져오기가 생성됩니다:
from . import resources_rc
디렉토리 트리
예를 들어 일부 프로젝트에는 더 복잡한 디렉터리 트리가 있습니다:
project resources (resources.qrc) ui (.ui files)
리소스 파일이 양식 소스와 같은 디렉터리에 있지 않고 .ui
파일은 일반적으로 리소스 파일에 대한 상대 경로를 갖습니다:
<include location="../resources/resources.qrc"/>
이 경우, 명령줄 옵션 --absolute-imports
을 사용하여 파이썬에서 절대 가져오기를 생성할 수 있습니다:
import resources.resources_rc
가 Python 가져오기 경로 목록에 포함된 프로젝트의 루트 디렉터리라는 가정에 따라 .
.
더 깊게 중첩된 트리의 경우 명령줄 옵션 --python-paths <path list>
을 사용하여 Python 가져오기 경로 목록을 전달할 수 있습니다. 그러면 uic
이 양식 파일 경로를 경로 구성 요소와 일치시켜 프로젝트 루트를 확인하려고 시도합니다.
--python-paths
을 지정하지 않으면 기본적으로 PYTHONPATH
환경 변수가 선택됩니다.
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.