跳到主要内容PyQt5 基础与常用控件入门教程 | 极客日志Python大前端
PyQt5 基础与常用控件入门教程
PyQt5 基础与常用控件入门教程涵盖了框架安装、窗口结构搭建及布局管理器的使用。内容包含 QLabel、QPushButton 等核心控件的代码实现与信号槽机制解析,帮助开发者快速掌握 Python 桌面应用界面的构建流程。
Eee_12349 浏览 PyQt5 基础与常用控件入门教程
前言
建议在实际 IDE 中运行代码查看效果,以便更好地理解界面构建过程。
第 1 部分:初识 PyQt5 和安装
1.1 什么是 PyQt5?
PyQt5 是 Python 的图形用户界面 (GUI) 框架,基于强大的 Qt 库。Qt 是一个跨平台的 C++ 框架,用于构建桌面应用程序。通过 PyQt5,我们可以用 Python 轻松构建跨平台的桌面应用程序,支持 Windows、macOS 和 Linux。
1.2 在 PyCharm 中安装 PyQt5
首先启动 PyCharm 编辑器,确保已创建或打开一个项目。安装 PyQt5 主要有两种方式:
- 方法 1:通过 PyCharm 设置安装
- 点击 File -> Settings。
- 选择 Project -> Python Interpreter。
- 点击右侧的 + 按钮,搜索 PyQt5。
- 选择 PyQt5 并点击 Install Package。
- 方法 2:通过终端安装
- 打开底部的 Terminal 窗口。
- 输入以下命令:
pip install PyQt5
- 安装完成后,PyCharm 会自动识别并添加 PyQt5 到项目中。
可以通过 pip list 检查是否安装成功。
1.3 在 PyCharm 中编写第一个 PyQt5 应用程序
接下来,我们创建一个简单的 PyQt5 应用程序,显示一个包含 "Hello, World!" 的窗口。
- 创建 Python 文件:在项目中右键点击文件夹,选择 New -> Python File,命名为
main.py。
- 编写代码:
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt5 第一个窗口")
label = QLabel("Hello, World!", self)
.setCentralWidget(label)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
self
1.4 代码详细解释
import sys:提供与 Python 解释器交互的功能,sys.exit() 确保程序关闭时干净退出。
QApplication:每个 PyQt5 程序必须有一个实例,管理控制流和设置。
QMainWindow:主窗口类,可包含菜单栏、工具栏等复杂结构。
QLabel:用于显示文本的基础控件。
setCentralWidget(label):将标签填充到窗口中间区域。
app.exec_():启动事件循环,保持程序运行直到关闭窗口。
1.5 在 PyCharm 中运行程序
确保代码保存后,点击顶部的绿色 Run 按钮即可看到窗口弹出。
1.6 常见问题排查
- 未安装 PyQt5:检查
pip list 确认环境。
- 解释器配置错误:确保 PyCharm 使用的 Python 版本与安装路径一致。
- 窗口不显示:检查是否调用了
window.show()。
1.7 总结
PyQt5 功能强大,适合创建桌面应用。通过几行代码即可搭建基本窗口框架。
第 2 部分:创建 PyQt5 应用程序与布局管理
2.1 PyQt5 的基本窗口结构
窗口是应用程序的核心。除了显示内容,我们还需要学习如何组织多个控件,使界面更具交互性和美观性。
2.2 基本的 PyQt5 窗口与布局
QWidget 与 QMainWindow 的区别
- QWidget:所有控件的基类,最基础的窗口控件。
- QMainWindow:高级窗口控件,继承自 QWidget,具备菜单栏、状态栏等功能。
2.3 布局管理器
- QVBoxLayout:垂直排列(从上到下)。
- QHBoxLayout:水平排列(从左到右)。
- QGridLayout:网格排列。
- QFormLayout:表单排列。
2.4 在窗口中使用布局管理器
我们来组合使用 QVBoxLayout 和 QHBoxLayout 组织控件。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt5 布局示例")
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
vbox_layout = QVBoxLayout()
label = QLabel("这是一个标签")
vbox_layout.addWidget(label)
hbox_layout = QHBoxLayout()
button1 = QPushButton("按钮 1")
button2 = QPushButton("按钮 2")
hbox_layout.addWidget(button1)
hbox_layout.addWidget(button2)
vbox_layout.addLayout(hbox_layout)
central_widget.setLayout(vbox_layout)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
QMainWindow 需要设置中央控件 (setCentralWidget)。
- 布局可以嵌套,例如将水平布局放入垂直布局中,实现灵活排版。
2.5 更多布局管理器介绍
QGridLayout (网格布局管理器)
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel, QPushButton
import sys
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("QGridLayout 示例")
layout = QGridLayout()
layout.addWidget(QLabel("标签 1"), 0, 0)
layout.addWidget(QPushButton("按钮 1"), 0, 1)
layout.addWidget(QLabel("标签 2"), 1, 0)
layout.addWidget(QPushButton("按钮 2"), 1, 1)
self.setLayout(layout)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
2.6 总结
本部分介绍了 QVBoxLayout、QHBoxLayout 和 QGridLayout 的使用。掌握这些布局管理器,无需手动计算坐标即可让界面自适应。
第 3 部分:常用控件详解
3.1 QLabel(标签)
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt5.QtCore import Qt
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QLabel 示例")
label = QLabel("这是一个标签", self)
label.setAlignment(Qt.AlignCenter)
self.setCentralWidget(label)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.2 QPushButton(按钮)
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QPushButton 示例")
button = QPushButton("点击我", self)
button.clicked.connect(self.button_clicked)
self.setCentralWidget(button)
def button_clicked(self):
print("按钮被点击!")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.3 QLineEdit(单行文本框)
from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QLineEdit 示例")
self.line_edit = QLineEdit(self)
self.line_edit.setPlaceholderText("请输入文本")
self.setCentralWidget(self.line_edit)
self.line_edit.returnPressed.connect(self.return_pressed)
def return_pressed(self):
text = self.line_edit.text()
print(f"用户输入:{text}")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.4 QCheckBox(复选框)
from PyQt5.QtWidgets import QApplication, QMainWindow, QCheckBox
from PyQt5.QtCore import Qt
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QCheckBox 示例")
self.checkbox = QCheckBox("同意条款", self)
self.checkbox.stateChanged.connect(self.checkbox_changed)
self.setCentralWidget(self.checkbox)
def checkbox_changed(self, state):
if state == Qt.Checked:
print("复选框被勾选")
else:
print("复选框未被勾选")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.5 QComboBox(下拉列表)
from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("QComboBox 示例")
self.combobox = QComboBox(self)
self.combobox.addItems(["选项 1", "选项 2", "选项 3"])
self.combobox.currentIndexChanged.connect(self.combobox_changed)
self.setCentralWidget(self.combobox)
def combobox_changed(self, index):
text = self.combobox.currentText()
print(f"当前选中:{text}")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.6 总结
介绍了 QLabel、QPushButton、QLineEdit、QCheckBox 和 QComboBox。这些控件构成了 GUI 应用的基础交互元素。
1-3 部分总结
前三部分涵盖了 PyQt5 的基础知识。从安装环境开始,创建了第一个窗口,学习了布局管理器来组织界面,最后深入探讨了常用控件及其信号槽机制。这些内容是构建复杂 Python 桌面应用的基石。
相关免费在线工具
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online
- JSON 压缩
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online