在Qt for Python 应用程序中使用设计器用户界面文件
将表单转换为 Python 代码
为了演示,我们使用Qt Widgets 动画缓和示例。
该应用程序由一个源文件easing.py
、一个用户界面文件form.ui
、一个资源文件easing.qrc
和一个项目文件easing.pyproject
组成,文件格式为 YAML:
{ "files": ["easing.qrc", "ui_form.py", "easing.py", "easing_rc.py", "form.ui"] }
用户界面文件通过User Interface Compiler (uic) 转换为 Python 代码,构建表单:
uic -g python form.ui > ui_form.py
由于顶层部件名为Form
,因此会生成一个名为Ui_Form
的 Python 类。它提供了一个以 widget 为参数的函数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
类访问这些 widget:
self.m_ui.graphicsView.setScene(self.m_scene)
除了setupUi()
之外,Ui_Form
还提供了另一个方法retranslateUi()
,该方法可在出现QEvent.LanguageChange 类型的QEvent 时调用,表示应用程序语言发生了变化。
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
在 Python 中生成绝对导入,结果如下:
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.