import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
# 创建一个中心窗口
central_widget = QWidget()
# 创建一个垂直布局
vbox = QVBoxLayout()
# 创建并添加按钮到布局
button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")
button3 = QPushButton("Button 3")
vbox.addWidget(button1)
vbox.addWidget(button2)
vbox.addWidget(button3)
# 将布局应用于中心窗口
central_widget.setLayout(vbox)
self.setCentralWidget(central_widget)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.2.2、水平布局管理器 QHBoxLayout:控件按照从左到右的顺序排列
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QPushButton
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
# 创建一个中心窗口
central_widget = QWidget()
# 创建一个水平布局
hbox = QHBoxLayout()
# 创建两个按钮并添加到水平布局中
button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")
button3 = QPushButton("Button 3")
hbox.addWidget(button1)
hbox.addWidget(button2)
hbox.addWidget(button3)
# 将水平布局应用于中心窗口
central_widget.setLayout(hbox)
self.setCentralWidget(central_widget)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.2.3、网格布局管理器 QGridLayout:指定每个控件所在的行和列
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QGridLayout, QPushButton
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
central_widget = QWidget()
self.setCentralWidget(central_widget)
grid_layout = QGridLayout()
central_widget.setLayout(grid_layout)
# 创建并添加多个按钮到网格布局
button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")
button3 = QPushButton("Button 3")
button4 = QPushButton("Button 4")
button5 = QPushButton("Button 5")
grid_layout.addWidget(button1, 0, 0) # 第一行第一列
grid_layout.addWidget(button2, 0, 1) # 第一行第二列
grid_layout.addWidget(button3, 1, 0) # 第二行第一列
grid_layout.addWidget(button4, 1, 1) # 第二行第二列
grid_layout.addWidget(button5, 1, 2, 1, 2) # 第二行的第三和第四列
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.2.4、表单布局管理器 QFormLayout:将标签和输入字段对齐,通常用于创建表单式的用户界面。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QFormLayout, QLineEdit, QLabel
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
# 创建一个中心窗口
central_widget = QWidget()
# 创建一个QFormLayout
form_layout = QFormLayout()
# 创建标签和相应的文本输入框,并将它们添加到QFormLayout
label1 = QLabel("Name:")
name_input = QLineEdit()
form_layout.addRow(label1, name_input)
label2 = QLabel("Email:")
email_input = QLineEdit()
form_layout.addRow(label2, email_input)
label3 = QLabel("Phone:")
phone_input = QLineEdit()
form_layout.addRow(label3, phone_input)
# 将QFormLayout应用于中心窗口
central_widget.setLayout(form_layout)
self.setCentralWidget(central_widget)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
3.2.5、堆叠布局管理器 QStackedLayout:在一个窗口中管理多个窗口且只显示一个窗口(如:选项卡界面)
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QLabel, QVBoxLayout, QStackedLayout
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
self.setWindowTitle("Stacked Layout Example")
# 创建两个页面的内容
self.page1 = self.create_page("Page 1 Content", "Switch to Page 2")
self.page2 = self.create_page("Page 2 Content", "Switch to Page 1")
# 创建一个堆叠布局管理器
self.stacked_layout = QStackedLayout()
# 将页面添加到堆叠布局
self.stacked_layout.addWidget(self.page1)
self.stacked_layout.addWidget(self.page2)
# 创建一个主窗口部件并将堆叠布局设置为其布局
central_widget = QWidget()
central_widget.setLayout(self.stacked_layout)
self.setCentralWidget(central_widget)
def create\_page(self, content_text, switch_button_text):
page = QWidget()
layout = QVBoxLayout()
content_label = QLabel(content_text)
switch_button = QPushButton(switch_button_text)
switch_button.clicked.connect(self.switch_page)
layout.addWidget(content_label)
layout.addWidget(switch_button)
page.setLayout(layout)
return page
def switch\_page(self):
# 切换页面
current_index = self.stacked_layout.currentIndex()
next_index = (current_index + 1) % 2 # 切换到下一页(循环切换)
self.stacked_layout.setCurrentIndex(next_index)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
四、PyQt 常用组件
4.1、简介
PyQt提供了丰富的组件(也称为控件或部件),用于构建图形用户界面。
组件(Widget) | 简介 | |
---|---|---|
窗口组件 | QWidget | 所有用户界面对象的基类,用于创建窗口和部件。 |
QMainWindow | 主窗口的类,通常用作应用程序的主界面。 | |
基础组件 | QLabel | 显示文本或图像。 |
QLineEdit | 输入单行文本。 | |
QTextEdit | 输入多行文本。 | |
QSpinBox | (数字)整数输入框。 | |
QDoubleSpinBox | (数字)浮点数输入框。 | |
QPushButton | 按钮。 | |
QRadioButton | 单选按钮。在多个选项中进行单选。 | |
QCheckBox | 复选框。在多个选项中进行多选。 | |
QSlider | 滑动条。 | |
QTabWidget | 选项卡界面。 | |
QComboBox | 下拉列表框。 | |
对话框类 - 组件 | QDialog | 自定义对话框 |
QInputDialog | 获取用户输入对话框 | |
QFontDialog | 字体对话框。 | |
QColorDialog | 颜色对话框。 | |
QProgressDialog | 进度对话框。 | |
QFileDialog | 打开文件/文件夹对话框。 | |
QMessageBox | 消息提示框。 | |
菜单类 - 组件 | QMenu | 菜单。 |
QMenuBar | 菜单栏。 | |
QToolBar | 工具栏。 | |
QStatusBar | 状态栏。 | |
QProgressBar | 进度条。 | |
绘图类 - 组件 | QGraphicsScene | 管理2D图形项的场景。 |
QGraphicsView | 显示二维图形和图像。 | |
QGraphicsItem | 在QGraphicsScene中显示图形项。 | |
QTableView | 显示表格数据。 | |
QTreeWidget | 显示树形数据。 | |
QListWidget | 显示列表数据。 | |
QCalendarWidget | 显示日历。 | |
QDockWidget | 创建可停靠的面板。 | |
QSplitter | 在界面中创建可调整大小的分割区域。 | |
QScrollArea | 显示超过容器尺寸的内容,并支持滚动查看。 |
4.2、项目实战
【菜单类 - 组件】菜单+菜单栏+工具栏+状态栏 QMenuBar + QMenu + QToolBar + QStatusBar
QAction用于表示用户界面上的动作或操作。它通常与菜单、工具栏和快捷键等用户界面元素一起使用,以便用户可以执行各种操作。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QMenuBar, QToolBar, QStatusBar, QAction, QTextEdit, QFileDialog
class MyWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
###################################################
# 创建菜单栏
menubar = self.menuBar()
# 创建文件菜单
file_menu = menubar.addMenu('File')
# 创建文件菜单项
new_action = QAction('New', self)
open_action = QAction('Open', self)
save_action = QAction('Save', self)
exit_action = QAction('Exit', self)
# 添加文件菜单项到文件菜单
file_menu.addAction(new_action)
file_menu.addAction(open_action)
file_menu.addAction(save_action)
file_menu.addSeparator() # 分隔线
file_menu.addAction(exit_action)
# 连接菜单项和工具按钮的槽函数
new_action.triggered.connect(self.newFile)
open_action.triggered.connect(self.openFile)
save_action.triggered.connect(self.saveFile)
exit_action.triggered.connect(self.exitApp)
###################################################
# 创建工具栏
toolbar = self.addToolBar('Toolbar')
# 在工具栏中添加工具按钮
new_button = toolbar.addAction('New') # 清空(当前)文本编辑框
open_button = toolbar.addAction('Open') # 打开txt文本并添加到文本编辑框
save_button = toolbar.addAction('Save') # 保存文本编辑框到txt文本
# 连接菜单项和工具按钮的槽函数
new_button.triggered.connect(self.newFile)
open_button.triggered.connect(self.openFile)
save_button.triggered.connect(self.saveFile)
###################################################
# 创建状态栏
statusbar = self.statusBar()
# 在状态栏中显示消息: 'Ready' 是要显示的文本消息,30000 是消息显示的时间(以毫秒为单位),即30秒。
statusbar.showMessage('Ready', 30000)
###################################################
# 创建文本编辑框
self.text_edit = QTextEdit(self)
self.setCentralWidget(self.text_edit) # 将文本编辑框设置为主窗口的中心组件
def newFile(self):
self.text_edit.clear() # 清空文本编辑框
def openFile(self):
try:
# 打开文件对话框,选择txt文件并读取内容,然后显示在文本编辑框中
file_dialog = QFileDialog(self)
file_path, _ = file_dialog.getOpenFileName()
if file_path:
with open(file_path, 'r', encoding='utf-8') as file:
file_contents = file.read()
self.text_edit.setPlainText(file_contents)
except Exception as e:
# 处理异常,例如显示错误消息
print(f"Error opening file: {str(e)}")
def saveFile(self):
try:
# 保存文件对话框,将文本编辑框中的内容保存到txt文件中
file_dialog = QFileDialog(self)
file_path, _ = file_dialog.getSaveFileName()
if file_path:
with open(file_path, 'w') as file:
file_contents = self.text_edit.toPlainText()
file.write(file_contents)
except Exception as e:
# 处理异常,例如显示错误消息
print(f"Error saving file: {str(e)}")
def exitApp(self):
self.close()
if __name__ == '\_\_main\_\_':
app = QApplication(sys.argv)
window = MyWindow()
window.setWindowTitle('PyQt Text Editor')
window.setGeometry(100, 100, 800, 300)
window.show()
sys.exit(app.exec_())
【对话框类 - 组件】输入对话框+颜色对话框+字体对话框+文件选择对话框+进度对话框+消息对话框:QInputDialog + QColorDialog + QFontDialog + QFileDialog + QProgressDialog + QMessageBox
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QInputDialog, QColorDialog, QFontDialog, QFileDialog, QProgressDialog, QMessageBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("Dialogs Example")
self.setGeometry(100, 100, 400, 300)
layout = QVBoxLayout()
# 显示输入对话框按钮
input_btn = QPushButton("Input Dialog")
input_btn.clicked.connect(self.show_input_dialog)
layout.addWidget(input_btn)
# 颜色对话框按钮
color_btn = QPushButton("Color Dialog")
color_btn.clicked.connect(self.show_color_dialog)
layout.addWidget(color_btn)
# 字体对话框按钮
font_btn = QPushButton("Font Dialog")
font_btn.clicked.connect(self.show_font_dialog)
layout.addWidget(font_btn)
# 打开文件对话框按钮
open_file_btn = QPushButton("Open File Dialog")
open_file_btn.clicked.connect(self.show_file_dialog)
layout.addWidget(open_file_btn)
# 进度对话框按钮
progress_btn = QPushButton("Progress Dialog")
progress_btn.clicked.connect(self.show_progress_dialog)
layout.addWidget(progress_btn)
# 消息框按钮
message_btn = QPushButton("Message Box")
message_btn.clicked.connect(self.show_message_box)
layout.addWidget(message_btn)
# 标签用于显示结果
self.result_label = QLabel()
layout.addWidget(self.result_label)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def show\_input\_dialog(self):
text, ok = QInputDialog.getText(self, "Input Dialog", "Enter something:")
if ok and text:
self.result_label.setText(f"Input: {text}")
else:
self.result_label.setText("Input Dialog Canceled")
def show\_color\_dialog(self):
color = QColorDialog.getColor(QColor(255, 0, 0), self, "Color Dialog")
if color.isValid():
self.result_label.setStyleSheet(f"background-color: {color.name()}")
self.result_label.setText(f"Selected Color: {color.name()}")
def show\_font\_dialog(self):
font, ok = QFontDialog.getFont(self)
if ok:
self.result_label.setFont(font)
self.result_label.setText(f"Selected Font: {font.family()}, {font.pointSize()}pt")
def show\_file\_dialog(self):
file_name, _ = QFileDialog.getOpenFileName(self, "Open File Dialog", "", "All Files (\*);;Text Files (\*.txt)")
if file_name:
self.result_label.setText(f"Selected File: {file\_name}")
def show\_progress\_dialog(self):
progress_dialog = QProgressDialog("Processing...", "Cancel", 0, 100, self)
progress_dialog.setWindowModality(Qt.WindowModal)
progress_dialog.setWindowTitle("Progress Dialog")
for i in range(100):
progress_dialog.setValue(i)
if progress_dialog.wasCanceled():
break
self.result_label.setText("Progress Dialog Completed")
def show\_message\_box(self):
msg_box = QMessageBox()
msg_box.setIcon(QMessageBox.Information)
msg_box.setWindowTitle("Message Box")
msg_box.setText("This is an information message box.")
msg_box.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
result = msg_box.exec_()
if result == QMessageBox.Ok:
self.result_label.setText("Message Box: Ok button clicked")
else:
self.result_label.setText("Message Box: Cancel button clicked")
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
4.2.0、设置组件属性:尺度 + 颜色 + 链接
# 设置尺度
self.button.setFixedSize(100, 35) # 设置组件的尺寸
self.button.setFixedWidth(35) # 设置组件的宽度
self.button.setFixedHeight(100) # 设置组件的高度
# 设置颜色(背景 + 字体) ———— 可以分别设置
self.button.setStyleSheet("background-color: green; color: white;")
# 设置链接到槽
self.checkbox.stateChanged.connect(self.function_checkbutton) # 将(复选框)信号连接到槽
self.slider.valueChanged.connect(self.function_slider) # 将(滑动条)信号连接到槽
self.LineEdit.returnPressed.connect(self.function_LineEdit) # 将(输入框)信号连接到槽
self.button.clicked.connect(self.function_button) # 将(按钮)信号连接到槽
4.2.1、显示文本 QLabel:Hello, PyQt!
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
app = QApplication([]) # 创建应用程序对象
window = QWidget() # 创建窗口对象
layout = QVBoxLayout() # 创建布局对象(垂直布局管理器)
label = QLabel('Hello, PyQt!') # 创建标签对象
layout.addWidget(label) # 将标签添加到布局中
window.setLayout(layout) # 将布局设置给窗口
window.show() # 显示窗口
app.exec_() # 运行应用程序
4.2.2、按钮 QPushButton:用户登录界面(账号与密码)
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout
class LoginWindow(QWidget):
def \_\_init\_\_(self):
super().__init__()
self.setWindowTitle("Login Window")
# 创建控件
self.username_label = QLabel("Username:")
self.username_edit = QLineEdit()
self.password_label = QLabel("Password:")
self.password_edit = QLineEdit()
self.login_button = QPushButton("Login")
self.login_button.clicked.connect(self.login) # 连接按钮点击事件到槽函数
self.result_label = QLabel("")
# 将容器部件添加到主布局中
layout = QVBoxLayout() # 垂直布局管理器
self.username_layout = QHBoxLayout() # 水平布局管理器
self.username_layout.addWidget(self.username_label) # 将文本框添加到水平布局管理器中
self.username_layout.addWidget(self.username_edit) # 将按钮添加到水平布局管理器中
layout.addLayout(self.username_layout) # layout.addLayout
self.password_layout = QHBoxLayout() # 水平布局管理器
self.password_layout.addWidget(self.password_label) # 将文本框添加到水平布局管理器中
self.password_layout.addWidget(self.password_edit) # 将按钮添加到水平布局管理器中
layout.addLayout(self.password_layout) # layout.addLayout
# 将登录按钮和结果标签添加到垂直布局中
layout.addWidget(self.login_button) # layout.addWidget
layout.addWidget(self.result_label) # layout.addWidget
# 设置窗口的主布局
self.setLayout(layout)
def login(self):
username = self.username_edit.text()
password = self.password_edit.text()
# 在这里可以编写登录验证逻辑,这里只是简单地判断用户名和密码是否为空
if username == 'you' and password == '66':
self.result_label.setText("Login successful!")
else:
self.result_label.setText("Please check username and password.")
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = LoginWindow()
window.show()
sys.exit(app.exec_())
4.2.3、文本框 QLineEdit + QTextEdit(单行 + 多行)
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QLineEdit, QTextEdit
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
# QLineEdit 示例
self.line_edit = QLineEdit(self)
layout.addWidget(QLabel("Single Line Input:"))
layout.addWidget(self.line_edit)
# QTextEdit 示例
self.text_edit = QTextEdit(self)
layout.addWidget(QLabel("Multi-line Text Input:"))
layout.addWidget(self.text_edit)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
# 连接槽函数
self.line_edit.textChanged.connect(self.show_line_edit_text)
self.text_edit.textChanged.connect(self.show_text_edit_text)
def show\_line\_edit\_text(self, text):
print("Line Edit Text:", text)
def show\_text\_edit\_text(self):
text = self.text_edit.toPlainText() # 获取 QTextEdit 的文本
print("Text Edit Text:", text)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
4.2.4、校验器 QRegExpValidator :用于限制用户在 QLineEdit 中输入的文本(英文 / 数字)
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLineEdit
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QRegExpValidator
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
self.line_edit = QLineEdit(self)
self.line_edit.setPlaceholderText("Enter English and numbers only")
# english\_only = QRegExp("[a-zA-Z]+") # 创建一个正则表达式,用于匹配只包含英文字符的文本
# numbers\_only = QRegExp("[0-9]+") # 创建一个正则表达式,用于匹配只包含数字的文本
regex = QRegExp("[A-Za-z0-9]+") # 创建一个正则表达式,只允许输入英文和数字
validator = QRegExpValidator(regex)
self.line_edit.setValidator(validator)
layout.addWidget(self.line_edit)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
"""
函数功能:QRegExp 类是 Qt 中用于处理正则表达式的类。
函数说明:QRegExp(pattern: str,
caseSensitivity: Qt.CaseSensitivity = Qt.CaseSensitive,
syntax: QRegExp.PatternSyntax = QRegExp.RegExp)
输入参数:
pattern 构造一个 QRegExp 对象,使用给定的正则表达式 pattern。
caseSensitivity 指定是否区分大小写,默认为区分大小写。
syntax 指定正则表达式的语法,默认为正则表达式语法。
"""
"""
函数功能:QRegExpValidator 类是 Qt 中用于输入验证的工具之一。它允许您使用正则表达式来限制用户在 QLineEdit 等控件中输入的文本。
函数说明:QRegExpValidator(regexp: QRegExp,
parent: QObject = None)
输入参数:
regexp 构造一个 QRegExpValidator 对象,使用给定的正则表达式 regexp 进行验证。
parent 用于设置对象的父级。
"""
4.2.5、校验器 QIntValidator + QDoubleValidator(整数 + 浮点数):用于限制用户在 QLineEdit 中输入的文本必须为数字。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QLabel, QLineEdit
from PyQt5.QtGui import QIntValidator, QDoubleValidator
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
int_label = QLabel("Enter an int between [0, 100]:")
int_label.setFixedWidth(350) # 设置固定的宽度
int_validator = QIntValidator(0, 100) # 创建QIntValidator,设置范围:[0, 100]
int_lineedit = QLineEdit() # 创建一个 QLineEdit 控件
int_lineedit.setValidator(int_validator) # 设置校验器
# 将校验器应用到QLineEdit控件中,用于限制用户只能输入 0 到 100 之间的整数。
double_label = QLabel("Enter an double between [0.0, 100.0]:")
double_label.setFixedWidth(350) # 设置固定的宽度
double_validator = QDoubleValidator(0.0, 100.0, 2) # 创建QDoubleValidator,设置范围:[0.0, 100.0],保留两位小数
double_lineedit = QLineEdit() # 创建一个 QLineEdit 控件
double_lineedit.setValidator(double_validator) # 设置校验器
# 将校验器应用到QDoubleValidator控件中,用于限制用户只能输入 0.0 到 100.0 之间的浮点数。
# 布局管理器
V_layout = QVBoxLayout()
H1_layout = QHBoxLayout()
H2_layout = QHBoxLayout()
H1_layout.addWidget(int_label)
H1_layout.addWidget(int_lineedit)
H2_layout.addWidget(double_label)
H2_layout.addWidget(double_lineedit)
V_layout.addLayout(H1_layout)
V_layout.addLayout(H2_layout)
# 将布局应用于主窗口的中心区域
central_widget = QWidget()
central_widget.setLayout(V_layout)
self.setCentralWidget(central_widget)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
"""##########################################################################
from PyQt5.QtGui import QIntValidator
函数简介:在输入框中,限制用户输入的内容必须是符合一定范围的整数。
函数说明:QIntValidator(bottom, top, parent=None)
输入参数:
bottom: 校验的最小值。
top: 校验的最大值。
parent: 可选,父对象。
属性: bottom(): 获取校验的最小值。
top(): 获取校验的最大值。
方法: setBottom(bottom): 设置校验的最小值。
setTop(top): 设置校验的最大值。
##########################################################################"""
"""##########################################################################
from PyQt5.QtGui import QDoubleValidator
函数简介:在输入框中,限制用户输入的内容必须是符合一定范围的整数。
函数说明:QDoubleValidator(bottom, top, decimals, parent=None)
输入参数:
bottom: 浮点数的最小值,用户输入的浮点数不能小于该值。
top: 浮点数的最大值,用户输入的浮点数不能大于该值。
decimals: 小数位数,表示允许的小数点后的位数。
parent: 可选参数,父级 QObject。
方法: bottom(): 返回校验器设置的最小值。
top(): 返回校验器设置的最大值。
decimals(): 返回校验器设置的小数位数。
setBottom(bottom: float): 设置校验器的最小值。
setTop(top: float): 设置校验器的最大值。
setDecimals(decimals: int): 设置校验器的小数位数。
##########################################################################"""
4.2.6、输入框 QSpinBox + QDoubleSpinBox(整数 + 浮点数):支持上下按钮调节
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QSpinBox, QDoubleSpinBox, QLabel
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
# 使用 QSpinBox 限制整数范围
QSpinBox_label = QLabel("int input:")
int_spinbox = QSpinBox()
int_spinbox.setRange(0, 100) # 限制范围:[0, 100]
# 使用 QDoubleSpinBox 限制浮点数范围
QDoubleSpinBox_label = QLabel("double input:")
double_spinbox = QDoubleSpinBox()
double_spinbox.setRange(0.0, 100.0) # 限制范围:[0.0, 100.0]
double_spinbox.setDecimals(2) # 保留2位小数
# 布局管理器
V_layout = QVBoxLayout() # 垂直布局
H1_layout = QHBoxLayout() # 水平布局
H2_layout = QHBoxLayout() # 水平布局
H1_layout.addWidget(QSpinBox_label)
H1_layout.addWidget(int_spinbox)
V_layout.addLayout(H1_layout)
H2_layout.addWidget(QDoubleSpinBox_label)
H2_layout.addWidget(double_spinbox)
V_layout.addLayout(H2_layout)
# 将布局应用于主窗口的中心区域
central_widget = QWidget()
central_widget.setLayout(V_layout)
self.setCentralWidget(central_widget)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
4.2.7、滑动条 QSlider:获取滑动条点击前后的值
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QSlider, QLabel
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
self.slider = QSlider()
self.slider.setOrientation(Qt.Horizontal)
self.slider.setRange(0, 100)
layout.addWidget(self.slider)
self.label = QLabel("Previous Value: 0, Current Value: 0")
layout.addWidget(self.label)
self.previous_value = 0
self.slider.valueChanged.connect(self.slider_value_changed)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def slider\_value\_changed(self, new_value):
self.label.setText(f"Previous Value: {self.previous\_value}, Current Value: {new\_value}")
self.previous_value = self.slider.value()
# self.slider.value():获取的是点击slider之后的值,而不是当前slider显示的值
if __name__ == "\_\_main\_\_":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
4.2.8、进度条 QProgressBar:创建一个进度条窗口(0~100%)
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QProgressBar
from PyQt5.QtCore import QTimer
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
# 设置窗口的几何属性
self.setGeometry(100, 100, 600, 200)
# 创建一个进度条并设置其几何属性
self.progress_bar = QProgressBar(self)
self.progress_bar.setGeometry(30, 40, 500, 25)
# 创建一个 "Start Progress" 按钮
start_button = QPushButton('Start Progress', self)
# 连接按钮的点击事件到 startProgress 函数
start_button.clicked.connect(self.startProgress)
# 设置按钮的固定宽度和位置
start_button.setFixedWidth(200)
start_button.move(30, 80)
def startProgress(self):
# 初始化进度为0
self.progress = 0
# 创建一个定时器
self.timer = QTimer(self)
# 连接定时器的超时事件到 updateProgress 函数
self.timer.timeout.connect(self.updateProgress)
# 每0.1秒触发一次定时器
self.timer.start(100)
def updateProgress(self):
# 增加进度
self.progress += 1
# 设置进度条的值
self.progress_bar.setValue(self.progress)
# 当进度达到100%时,停止定时器
if self.progress >= 100:
self.timer.stop()
if __name__ == '\_\_main\_\_':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
4.2.9、下拉框 QComboBox:创建一个下拉框并添加选项
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QComboBox
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
label = QLabel("Select an option:")
layout.addWidget(label)
combo_box = QComboBox()
combo_box.addItem("Option 1")
combo_box.addItem("Option 2")
combo_box.addItem("Option 3")
combo_box.currentIndexChanged.connect(self.selection_changed) # 连接选项变更事件
layout.addWidget(combo_box)
self.result_label = QLabel("", self)
layout.addWidget(self.result_label)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def selection\_changed(self, index):
selected_option = self.sender().currentText()
self.result_label.setText(f"Selected: {selected\_option}")
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
4.2.10、复选框 Check Box:获取勾选状态
获取复选框状态:
self.checkbox.stateChanged.connect()
通过复选框的 checkState() 方法可以获取其当前的状态值:0、1 或 2
。分别表示未选中、选中和部分选中(半选中)
的状态。
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QCheckBox, QLabel
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
self.checkbox = QCheckBox("Image", self)
self.checkbox.setChecked(True) # 默认选中复选框
self.checkbox.stateChanged.connect(self.invert_load_image)
self.label = QLabel("") # 创建一个用于显示图像名称的QLabel
layout.addWidget(self.checkbox)
layout.addWidget(self.label)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def invert\_load\_image(self, state):
if state == 2: # 部分选中状态
self.label.setText("选中复选框")
elif state == 0: # 未选中状态
self.label.setText("未选中复选框")
# 连接到加载图像的槽函数
self.load_image()
def load\_image(self):
# 加载图像的相关操作
print("加载图像...")
if __name__ == "\_\_main\_\_":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
获取复选框状态:
self.checkbox.isChecked()
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QCheckBox
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
# 创建多个复选框
self.checkbox1 = QCheckBox("Option 1", self)
self.checkbox2 = QCheckBox("Option 2", self)
self.checkbox3 = QCheckBox("Option 3", self)
layout.addWidget(self.checkbox1)
layout.addWidget(self.checkbox2)
layout.addWidget(self.checkbox3)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
# 连接按钮的点击信号到槽函数
self.checkbox1.clicked.connect(self.show_states)
self.checkbox2.clicked.connect(self.show_states)
self.checkbox3.clicked.connect(self.show_states)
def show\_states(self):
# 获取每个复选框的状态并显示
state1 = self.checkbox1.isChecked()
state2 = self.checkbox2.isChecked()
state3 = self.checkbox3.isChecked()
print("Option 1 is checked:", state1)
print("Option 2 is checked:", state2)
print("Option 3 is checked:", state3)
if __name__ == "\_\_main\_\_":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
4.2.11、单选按钮 QRadioButton:获取勾选状态
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QRadioButton, QLabel, QButtonGroup
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
# 新建单选按钮。在多个选项中进行单选。
self.group_radio_buttons = []
self.group_label = []
group_options = ["Option1", "Option2", "Option3"] # 单选按钮名称
group_label_options = ["signal", "double", "double"] # 初始化标签值
self.group_button_group = QButtonGroup()
for index, option in enumerate(group_options):
hbox = QHBoxLayout()
radio_button = QRadioButton(option) # 添加单选按钮
radio_button.setFixedWidth(150) # 设置宽度
label = QLabel(group_label_options[index]) # 添加标签
self.group_radio_buttons.append(radio_button) # 保存三个radio按钮
self.group_label.append(label) # 保存三个label标签
self.group_button_group.addButton(radio_button, index)
# 添加布局
hbox.addWidget(radio_button)
hbox.addWidget(label)
layout.addLayout(hbox)
# if option == "Option1": # 设置 "YZ" 默认选中
# radio\_button.setChecked(True)
self.group_button_group.buttonClicked.connect(self.update_result_label)
# 新建结果打印标签
self.result_label = QLabel("Selected:", self)
layout.addWidget(self.result_label)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def update\_result\_label(self):
selected_option = None
for index, button in enumerate(self.group_radio_buttons):
if button.isChecked():
selected_option = button.text()
break
if selected_option is not None:
self.result_label.setText(f"Selected: {selected\_option}")
else:
self.result_label.setText("No option selected")
if selected_option == "Option1":
self.group_label[0].setText(str(1))
else:
self.group_label[0].setText("")
if selected_option == "Option2":
self.group_label[1].setText(str(2))
else:
self.group_label[1].setText("")
if selected_option == "Option3":
self.group_label[2].setText(str(3))
else:
self.group_label[2].setText("")
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
只给part_brain添加文本框;且只有选择part_brain时,文本框状=True。
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QRadioButton, QLineEdit, QButtonGroup
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
self.group_radio_buttons = []
self.group_line = []
group_options = ["part\_brain", "whole\_image"]
self.group_button_group = QButtonGroup()
for index, option in enumerate(group_options):
radio_button = QRadioButton(option)
self.group_radio_buttons.append(radio_button)
self.group_button_group.addButton(radio_button, index)
layout.addWidget(radio_button)
if option == "part\_brain":
line_edit = QLineEdit(self)
self.group_line.append(line_edit)
line_edit.setEnabled(False) # 只有 "part\_brain" 被选中时启用文本框
layout.addWidget(line_edit)
if option == "whole\_image":
radio_button.setChecked(True)
self.group_button_group.buttonClicked.connect(self.update_line_edit_status)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def update\_line\_edit\_status(self):
for index, button in enumerate(self.group_radio_buttons):
if button.isChecked():
if index < len(self.group_line):
self.group_line[index].setEnabled(True)
else:
for line_edit in self.group_line:
line_edit.setEnabled(False)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
4.2.12、打印日志 QTextEdit:获取当前时间 + 设置文本颜色
from PyQt5.QtWidgets import QApplication, QTextEdit, QVBoxLayout, QPushButton, QMainWindow, QWidget
from PyQt5.QtCore import Qt, QDateTime
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
layout = QVBoxLayout()
self.log_text_edit = QTextEdit()
layout.addWidget(self.log_text_edit)
self.button = QPushButton("Print Current Time")
self.button.clicked.connect(self.print_current_time)
layout.addWidget(self.button)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def print\_current\_time(self):
current_time1 = QDateTime.currentDateTime().toString(Qt.DefaultLocaleLongDate) # 指定默认格式
current_time2 = QDateTime.currentDateTime().toString("yyyy-M-d hh:mm:ss") # 指定日期格式
message = current_time1 + r'<font color="red"> + {}</font>'.format(current_time2)
self.log_text_edit.append(message)
if __name__ == '\_\_main\_\_':
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
from datetime import datetime
current_time = datetime.now() # 获取当前时间
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("Time:", formatted_time) # 打印格式化后的时间
# Time: 2023-08-08 14:25:29
4.2.13、消息提示框 QMessageBox:四种类型提示框(信息 / 询问 / 警告 / 错误)
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QMessageBox
class MainWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
layout = QVBoxLayout(central_widget)
info_button = QPushButton("Information")
info_button.clicked.connect(self.show_information)
layout.addWidget(info_button)
question_button = QPushButton("Question")
question_button.clicked.connect(self.show_question)
layout.addWidget(question_button)
warning_button = QPushButton("Warning")
warning_button.clicked.connect(self.show_warning)
layout.addWidget(warning_button)
critical_button = QPushButton("Critical")
critical_button.clicked.connect(self.show_critical)
layout.addWidget(critical_button)
def show\_information(self):
QMessageBox.information(self, "Information", "This is an information message.", QMessageBox.Ok, QMessageBox.Ok)
def show\_question(self):
result = QMessageBox.question(self, "Question", "Do you want to proceed?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if result == QMessageBox.Yes:
print("User clicked Yes")
else:
print("User clicked No")
def show\_warning(self):
QMessageBox.warning(self, "Warning", "This is a warning message.", QMessageBox.Ok, QMessageBox.Ok)
def show\_critical(self):
QMessageBox.critical(self, "Critical", "This is a critical message.", QMessageBox.Ok, QMessageBox.Ok)
if __name__ == "\_\_main\_\_":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
"""##########################################################################
from PyQt5.QtWidgets import QMessageBox
函数简介:用于显示消息框、询问框、警告框等用户交互提示框的类。
函数说明:
信息消息框 QMessageBox.information(parent, title, message, buttons, defaultButton)
询问消息框 QMessageBox.question(parent, title, message, buttons, defaultButton)
警告消息框 QMessageBox.warning(parent, title, message, buttons, defaultButton)
严重错误消息框 QMessageBox.critical(parent, title, message, buttons, defaultButton)
输入参数:
parent: 可选参数,父级窗口。
title: 消息框的标题。
message: 消息框中显示的消息文本。
buttons: 消息框中显示的按钮类型,如 QMessageBox.Yes、QMessageBox.No 等。
defaultButton: 可选参数,指定默认按钮。
##########################################################################"""
4.2.14、选项卡界面 QTabWidget
4.2.14.1、在一个窗口中显示多个页面
Tab控件:可以在一个窗口中显示多个页面,每个页面对应一个选项卡,用户可以通过点击选项卡来切换不同的页面。
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout, QLabel
class MyWindow(QMainWindow):
def \_\_init\_\_(self):
super().__init__()
# 创建Tab控件
self.tab_widget = QTabWidget()
self.setCentralWidget(self.tab_widget)
# 创建页面并添加到Tab控件中
self.page1 = QWidget()
self.page2 = QWidget()
self.tab_widget.addTab(self.page1, "Page 1")
self.tab_widget.addTab(self.page2, "Page 2")
# 设置页面的布局和内容
layout1 = QVBoxLayout()
layout1.addWidget(QLabel("This is Page 1"))
self.page1.setLayout(layout1)
layout2 = QVBoxLayout()
layout2.addWidget(QLabel("This is Page 2"))
self.page2.setLayout(layout2)
if __name__ == "\_\_main\_\_":
app = QApplication([])
window = MyWindow()
window.show()
app.exec_()
4.2.14.2、在主界面中,显示其他.py界面类文件
实现选项卡自动显示不同界面,可以在主界面的初始化过程中创建并添加不同的界面类实例,并根据选项卡的切换来显示相应的界面。
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)
self.page2 = QWidget()
self.tab_widget.addTab(self.page1, "Page 1")
self.tab_widget.addTab(self.page2, "Page 2")
# 设置页面的布局和内容
layout1 = QVBoxLayout()
layout1.addWidget(QLabel("This is Page 1"))
self.page1.setLayout(layout1)
layout2 = QVBoxLayout()
layout2.addWidget(QLabel("This is Page 2"))
self.page2.setLayout(layout2)
if name == “__main__”:
app = QApplication([])
window = MyWindow()
window.show()
app.exec_()
#### 4.2.14.2、在主界面中,显示其他.py界面类文件
>
> 实现选项卡自动显示不同界面,可以在主界面的初始化过程中创建并添加不同的界面类实例,并根据选项卡的切换来显示相应的界面。
> ![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/42a190a2c1b9ec4ffe6e1b67eba9b552.png)
>
**自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。**
**深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!**
**因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**
[外链图片转存中...(img-lUmoYE8n-1713603416359)]
[外链图片转存中...(img-wF0cW6LB-1713603416360)]
[外链图片转存中...(img-I2NwHQiN-1713603416360)]
[外链图片转存中...(img-bIoB5HVd-1713603416361)]
![img](https://i-blog.csdnimg.cn/blog_migrate/3443f3d934f11d6666b3767ac0897763.png)
![img](https://i-blog.csdnimg.cn/blog_migrate/0426b4c2e3d69852ceb846faa8ff365f.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!**
**由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新**
**如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)**
![](https://img-blog.csdnimg.cn/img_convert/ed095ff0f0fb19737fdd06d26f128f43.jpeg)