教程: Qt Widgets 用户界面和 Python
首先,创建Qt for Python 应用程序项目。然后,使用集成的Qt Widgets Designer 设计基于部件的用户界面。
有关创建Qt for Python 应用程序的更多示例,请参阅Qt for Python 示例和教程。
创建窗口用户界面项目
要创建一个Qt for Python 应用程序,其中包含一个主类的源文件:
- 转到File >New Project 。
- 选择 Application (Qt for Python)>Window UI >Choose ,打开Project Location 对话框。
- 在Name 中,输入项目名称。例如,hello_world_ui。
- 在Create in 中,输入项目文件的路径。例如,
C:\Examples
。 - 选择Next (Windows 和 Linux)或Continue (macOS),打开Define Class 对话框。
- 在Class name 中,选择MainWindow作为类名。
- 在Base class 中,选择 QMainWindow作为基类。
注意: Source file 字段会自动更新,以匹配类的名称。
- 在Project file 中,输入项目文件的名称。
- 选择Next 或Continue ,打开Define Python Interpreter 对话框。
- 在PySide version 中,选择生成代码的 PySide 版本。
- 选择Next 或Continue ,打开Kit Selection 对话框。
- 选择用于构建、部署和运行项目的 Python 工具包。默认情况下,这会在源代码目录内为项目创建一个虚拟环境。要使用全局解释器,请选择与Details 中工具包的 Python 名称相同的构建配置。
- 选择Next 或Continue 。
- 查看项目设置,然后选择Finish (在 Windows 和 Linux 上)或Done (在 macOS 上)创建项目。
向导会生成以下文件:
form.ui
,这是窗口用户界面的用户界面文件。pyproject.toml
该文件列出了 Python 项目中的文件和其他配置。mainwindow.py
, 其中包含一些类的模板代码。requirements.txt
保存了生成代码的 PySide 版本。你可以使用这个文件,用 pip 安装所需的 PySide 版本。
为项目安装 PySide6
在Edit 模式下,选择Install 为项目安装 PySide6。
设计基于 widgets 的用户界面
- 在Edit 模式下,双击Projects 视图中的
form.ui
文件,启动集成的Qt Widgets Designer。 - 将下列部件从Widget Box 拖到表单中:
- Text Edit ( )QTextEdit
- Check Box ( )QCheckBox
- Push Button ( )QPushButton
注: 要轻松查找部件,请使用Widget Box 顶部的搜索框。例如,要查找Text Edit 部件,请开始键入文本一词。
- 双击Text Edit 小工具并输入文本在此输入文本。
- 双击Check Box Widget 并输入文本 "选择我"。
- 双击Push Button Widget 并输入文本 "单击我"。
- 选择Ctrl+S(或Cmd+S)保存更改。
有关使用Qt Widgets Designer 设计用户界面的更多信息,请参阅Qt Widgets Designer Manual。
运行应用程序
选择 (Run) 运行应用程序。
另请参阅 教程:Qt Quick 和 Python、教程:Qt Widgets 和 Python 以及开发Qt for Python 应用程序。
Copyright © The Qt Company Ltd. and other contributors. 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.