在您的Qt for Python 应用程序中使用Qt Widgets Designer UI文件
将表单转换为 Python 代码
为了演示,我们将使用Qt Widgets 的动画缓动示例。
该应用程序由一个源文件 `easing.py`、一个 UI 文件 `form.ui ` 以及一个 TOML 格式的项目文件 `pyproject.toml` 组成:
[project]
name = "Easing Example"
[tool.pyside6-project]
files = ["easing.py", "form.ui"]UI 文件被转换为 Python 代码,该代码使用 `User Interface Compiler `(uic)来构建表单:
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 还提供另一个方法retranslateUi() ,该方法可在接收到类型为QEvent.LanguageChange 的QEvent 时被调用,该事件表示应用程序语言发生了变化。
UiTools 方法
QUiLoader 类提供了一个表单加载器对象,用于在运行时构建用户界面。该用户界面可从任何QIODevice 中获取,例如QFile 对象。QUiLoader::load()函数使用文件中包含的用户界面描述来构建表单控件。
uiloader示例对此进行了演示:
from PySide6.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.OpenModeFlag.ReadOnly):
print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
sys.exit(-1)
loader = QUiLoader()
widget = loader.load(ui_file, None)
ui_file.close()
if widget is None:
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 。
© 2026 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.