教程:Qt Widgets 和 Python
首先,创建Qt for Python 应用程序项目。然后,编辑模板代码,开发一个使用 Qt Widgets 以多种语言显示文本Hello World的小型应用程序。
有关创建Qt for Python 应用程序的更多示例,请参阅Qt for Python 示例和教程。
创建一个空窗口项目
创建一个Qt for Python 应用程序,其中包含一个主类的源文件:
- 转到File >New Project 。
- 选择 Application (Qt for Python)>Empty Window >Choose ,打开Project Location 对话框。
- 在Name 中,输入项目名称。例如,hello_world。
- 在Create in 中,输入项目文件的路径。例如,
C:\Examples
。 - 选择Next (Windows 和 Linux)或Continue (macOS),打开Define Class 对话框。
- 在Class name 中,输入MyWidget作为类名。
- 在Base class 中,选择 QWidget作为基类。
注意: Source file 字段会自动更新,以匹配类的名称。
- 在Project file 中,输入项目文件的名称。
- 选择Next 或Continue ,打开Define Project Details 对话框。
- 在PySide version 中,选择生成代码的 PySide 版本。
- 选择Next 或Continue ,打开Kit Selection 对话框。
- 选择用于构建、部署和运行项目的 Python 工具包。默认情况下,这会在源代码目录内为项目创建一个虚拟环境。要使用全局解释器,请选择与Details 中工具包的 Python 名称相同的构建配置。
- 选择Next 或Continue 。
- 查看项目设置,然后选择Finish (在 Windows 和 Linux 上)或Done (在 macOS 上)创建项目。
向导会生成以下文件:
pyproject.toml
该文件列出了 Python 项目中的文件和其他配置。mywidget.py
,其中包含一些类的模板代码。requirements.txt
保存生成代码的 PySide 版本。你可以使用这个文件,用 pip 安装所需的 PySide 版本。
为项目安装 PySide6
在Edit 模式下,选择Install 为项目设置 PySide6。
添加Qt Widgets 导入
向导会将导入添加到mywidget.py
源文件,以便访问QApplication 和在Qt Widgets 模块中选择的基类QWidget 。此外,还需要导入random
和QtCore 用于随机选择显示文本的语言,以及QtWidgets 用于添加 UI 元素:
import sys import random from PySide6.QtWidgets import QApplication, QWidget from PySide6 import QtCore, QtWidgets
添加基于部件的用户界面
向导会添加一个具有指定名称的主类,该主类继承自指定的基类:
class MyWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) ...
添加按钮、标签和布局部件,创建用户界面元素:
... self.hello = ["Hallo Welt", "Hei maailma", "Hola Mundo", "Привет мир"] self.button = QtWidgets.QPushButton("Click me!") self.text = QtWidgets.QLabel("Hello World", alignment=QtCore.Qt.AlignCenter) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.text) self.layout.addWidget(self.button) ...
添加信号和槽
然后,添加一个信号和一个槽来实现随机函数:
... self.button.clicked.connect(self.magic) @QtCore.Slot() def magic(self): self.text.setText(random.choice(self.hello))
添加主函数
向导添加了一个主函数,并在其中创建了一个QApplication 实例。由于 Qt XML 可以从命令行接收参数,因此您可以向QApplication 对象传递任何参数。通常,您不需要传递任何参数,可以使用以下方法:
if __name__ == "__main__": app = QApplication(sys.argv) ...
实例化 MainWindow 类
向导会实例化MainWindow
类并显示出来:
... widget = MyWidget() widget.show() ...
执行 Qt 代码
最后,向导调用app.exec()
方法,进入 Qt 主循环并开始执行 Qt 代码:
... sys.exit(app.exec())
运行应用程序
选择 (Run) 运行应用程序。
另请参阅 教程:Qt Quick 和 Python、教程:UI和 Python,以及 开发Qt 应用程序: Qt Widgets UI 和 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.