本页内容

教程:Qt Widgets 用户界面与 Python

首先,创建一个Qt for Python 应用程序项目。然后,使用集成的Qt Widgets 设计器来设计基于小部件的用户界面。

一个小型 Qt Widgets 应用程序

有关创建Qt for Python 应用程序的更多示例,请参阅《Qt for Python 示例与教程》

创建窗口式 UI 项目

若要创建一个包含主类源文件的Qt for Python 应用程序:

  1. 转到“File ” > “New Project ”。
  2. 选择 Application (Qt for Python) >Window UI >Choose ,以打开“Project Location ”对话框。

    “项目位置”对话框

  3. 在“Name ”中,输入项目名称。例如,hello_world_ui
  4. 在“Create in ”中,输入项目文件的路径。例如,C:\Examples
  5. 选择“Next ”(Windows 和 Linux 系统)或“Continue ”(macOS 系统)以打开“Define Class ”对话框。

    “定义类”对话框

  6. 在“Class name ”中,选择“MainWindow”作为类名。
  7. Base class 中,选择 QMainWindow 作为基类。

    注意:“ Source file ”字段 会自动更新,以匹配类名。

  8. 在“Project file ”中,输入项目文件的名称。
  9. 选择“Next ”或“Continue ”以打开“Define Python Interpreter ”对话框。

    “定义 Python 解释器”对话框

  10. 在“PySide version ”中,选择生成的代码的 PySide 版本。
  11. 选择“Next ”或“Continue ”以打开“Kit Selection ”对话框。

    为 Python 项目选择开发套件

  12. 选择用于构建、部署和运行项目的 Python 工具包。默认情况下,这会在源代码目录内为项目创建一个虚拟环境。若要使用全局解释器,请选择与“Details ”中该工具包的 Python 名称相同的构建配置。
  13. 选择“Next ”或“Continue ”。
  14. 检查项目设置,并选择Finish (Windows 和 Linux 系统)或Done (macOS 系统)以创建项目。

向导将生成以下文件:

  • form.ui,这是窗口用户界面的 UI 文件。
  • pyproject.toml,其中列出了 Python 项目中的文件及其他配置。
  • mainwindow.py,其中包含类的一些模板代码。
  • requirements.txt,用于存储生成的代码对应的 PySide 版本。您可以使用此文件通过 pip 安装所需的 PySide 版本。

为项目安装 PySide6

在“Edit ”模式下,选择“Install ”为项目配置 PySide6。

提示安装 PySide6

设计基于小部件的用户界面

  1. 在“Edit ”模式下,双击“Projects ”视图中的form.ui 文件,以启动集成的Qt Widgets Designer。
  2. 将以下控件从Widget Box 拖放到表单上:

    向用户界面添加小部件

    注意:要 轻松找到控件,请使用Widget Box 顶部的搜索框。例如,要查找“Text Edit ”控件,请开始输入“text”一词。

  3. 双击“Text Edit ”控件,并输入文本“Enter text here”
  4. 双击“Check Box ”小部件,并输入文本“Select me”。
  5. 双击“Push Button ”控件,并输入文本“Click me”。
  6. Ctrl+S(或Cmd+S)保存更改。

有关使用Qt Widgets Designer 设计 UI 的更多信息,请参阅《Qt Widgets Designer 手册》。

运行应用程序

选择““运行”按钮 ”(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.