在本节中我们将设置一个表格,并为其添加表头和内容显示功能。首先,通过顶部的按钮组的设置后,我们来配置表格的表头信息,并逐步完善表格的数据填充和展示功能。
设置表头
我们首先设置表格的表头。在 self.table_widget 中,使用 setHorizontalHeaderLabels 方法来设定表头内容。需要注意的是,在表头中,我们会使用一个单选框作为图标,如下图所示:
但由于图标无法直接作为文本显示,这里将其位置暂时留空,后续再进行处理。接下来我们使用 self.table_widget.setColumnCount 方法来定义列数,并将其设置为 11 列。代码如下:
# student_interface.py 文件
import sys # 导入 sys 模块,用于处理系统相关的功能
# 从 PyQt6.QtWidgets 模块中导入 QWidget、QVBoxLayout、QHBoxLayout、QApplication 和 QHeaderView
# 分别用于创建窗口部件、垂直布局、水平布局、应用程序以及表格头部视图
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QApplication, QHeaderView
# 从 qfluentwidgets 库中导入 CardWidget、PushButton、SearchLineEdit、TableWidget、setCustomStyleSheet
# 用于创建卡片样式的组件、按钮、搜索输入框、表格组件以及设置自定义样式
from qfluentwidgets import CardWidget, PushButton, SearchLineEdit, TableWidget, setCustomStyleSheet
# 导入自定义样式,用于“新增”和“批量删除”按钮
from utils.custom_style import ADD_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
# 定义 StudentInterface 类,继承自 QWidget
class StudentInterface(QWidget):
def __init__(self): # 初始化方法
super().__init__() # 调用父类 QWidget 的初始化方法
self.setObjectName("studentInterface") # 设置当前界面的对象名称
self.setup_ui() # 调用 setup_ui 方法,配置界面布局和组件
def setup_ui(self): # 定义 setup_ui 方法,用于设置界面的布局和组件
layout = QVBoxLayout(self) # 创建垂直布局,并将其设置为当前窗口的主布局
# 顶部按钮组
card_widget = CardWidget(self) # 创建卡片样式的组件作为按钮组容器,并设置父组件为当前窗口
buttons_layout = QHBoxLayout(card_widget) # 创建水平布局,用于放置按钮,并将其设置为 card_widget 的布局
self.addButton = PushButton("新增", self) # 创建一个“新增”按钮,并将其设置为当前窗口的子组件
setCustomStyleSheet(self.addButton, ADD_BUTTON_STYLE, ADD_BUTTON_STYLE) # 应用自定义样式
# 创建搜索输入框
self.searchInput = SearchLineEdit(self) # 创建一个搜索输入框,并将其设置为当前窗口的子组件
self.searchInput.setPlaceholderText("搜索学生姓名或学号...") # 设置占位提示文字
self.searchInput.setFixedWidth(500) # 设置输入框固定宽度为 500
# 创建“批量删除”按钮并应用自定义样式
self.batchDeleteButton = PushButton("批量删除", self)
setCustomStyleSheet(self.batchDeleteButton, BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE)
# 将按钮和搜索框添加到按钮组的水平布局中
buttons_layout.addWidget(self.addButton) # 添加“新增”按钮
buttons_layout.addWidget(self.searchInput) # 添加搜索输入框
buttons_layout.addStretch(1) # 添加弹性空间,将按钮推向两端
buttons_layout.addWidget(self.batchDeleteButton) # 添加“批量删除”按钮
# 将按钮组的卡片组件添加到主布局中
layout.addWidget(card_widget)
# 表格组件(创建空表格,后续填充内容)
self.table_widget = TableWidget(self)
self.table_widget.setBorderVisible(True) # 设置表格边框可见
self.table_widget.setBorderRadius(8) # 设置表格圆角
self.table_widget.setWordWrap(False) # 禁用自动换行
# 设置表头填充模式和列数
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch) # 表头填充模式为 Stretch,使表头填满整个表格,并实现列宽自适应屏幕缩放的效果。
self.table_widget.setColumnCount(11) # 设置表格列数为 11 列
self.table_widget.setHorizontalHeaderLabels(
["", "学生ID", "姓名", "学号", "性别", "班级", "语文", "数学", "英语", "总分", "操作"]) # 设置表头名称
# 将表格组件添加到主布局中
layout.addWidget(self.table_widget)
self.setStyleSheet("StudentInterface{background: white}") # 设置界面背景为白色
self.resize(1280, 760) # 设置窗口大小为 1280x760
# 主程序入口
if __name__ == '__main__':
app = QApplication(sys.argv) # 创建应用程序实例
window = StudentInterface() # 创建 StudentInterface 窗口实例
window.show() # 显示窗口
sys.exit(app.exec()) # 进入应用程序主循环,并在退出时返回状态码
完成设置后,可以运行代码查看表头显示效果,如下图所示:
填充表格数据
表格的初始状态是空的。为了展示数据,我们首先构造一些假数据,并在student_interface.py文件中定义 load_data 函数进行加载。假数据存储在 self.students 属性中,该属性是一个列表,列表中的每个元素是一个字典,模拟与数据库中数据字段一一对应的结构。代码如下:
# student_interface.py 文件
import sys # 导入 sys 模块,用于处理系统相关的功能
# 从 PyQt6.QtWidgets 模块中导入 QWidget、QVBoxLayout、QHBoxLayout、QApplication 和 QHeaderView
# 分别用于创建窗口部件、垂直布局、水平布局、应用程序以及表格头部视图
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QApplication, QHeaderView
# 从 qfluentwidgets 库中导入 CardWidget、PushButton、SearchLineEdit、TableWidget、setCustomStyleSheet
# 用于创建卡片样式的组件、按钮、搜索输入框、表格组件以及设置自定义样式
from qfluentwidgets import CardWidget, PushButton, SearchLineEdit, TableWidget, setCustomStyleSheet
# 导入自定义样式,用于“新增”和“批量删除”按钮
from utils.custom_style import ADD_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
# 定义 StudentInterface 类,继承自 QWidget
class StudentInterface(QWidget):
def __init__(self): # 初始化方法
super().__init__() # 调用父类 QWidget 的初始化方法
self.setObjectName("studentInterface") # 设置当前界面的对象名称
self.students = [] # 用于存储学生数据的列表
self.setup_ui() # 调用 setup_ui 方法,配置界面布局和组件
def setup_ui(self): # 定义 setup_ui 方法,用于设置界面的布局和组件
layout = QVBoxLayout(self) # 创建垂直布局,并将其设置为当前窗口的主布局
# 顶部按钮组
card_widget = CardWidget(self) # 创建卡片样式的组件作为按钮组容器,并设置父组件为当前窗口
buttons_layout = QHBoxLayout(card_widget) # 创建水平布局,用于放置按钮,并将其设置为 card_widget 的布局
self.addButton = PushButton("新增", self) # 创建一个“新增”按钮,并将其设置为当前窗口的子组件
setCustomStyleSheet(self.addButton, ADD_BUTTON_STYLE, ADD_BUTTON_STYLE) # 应用自定义样式
# 创建搜索输入框
self.searchInput = SearchLineEdit(self) # 创建一个搜索输入框,并将其设置为当前窗口的子组件
self.searchInput.setPlaceholderText("搜索学生姓名或学号...") # 设置占位提示文字
self.searchInput.setFixedWidth(500) # 设置输入框固定宽度为 500
# 创建“批量删除”按钮并应用自定义样式
self.batchDeleteButton = PushButton("批量删除", self)
setCustomStyleSheet(self.batchDeleteButton, BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE)
# 将按钮和搜索框添加到按钮组的水平布局中
buttons_layout.addWidget(self.addButton) # 添加“新增”按钮
buttons_layout.addWidget(self.searchInput) # 添加搜索输入框
buttons_layout.addStretch(1) # 添加弹性空间,将按钮推向两端
buttons_layout.addWidget(self.batchDeleteButton) # 添加“批量删除”按钮
# 将按钮组的卡片组件添加到主布局中
layout.addWidget(card_widget)
# 表格组件(创建空表格,后续填充内容)
self.table_widget = TableWidget(self)
self.table_widget.setBorderVisible(True) # 设置表格边框可见
self.table_widget.setBorderRadius(8) # 设置表格圆角
self.table_widget.setWordWrap(False) # 禁用自动换行
# 设置表头填充模式和列数
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch) # 表头填充模式为 Stretch,使表头填满整个表格,并实现列宽自适应屏幕缩放的效果
self.table_widget.setColumnCount(11) # 设置表格列数为 11 列
self.table_widget.setHorizontalHeaderLabels(
["", "学生ID", "姓名", "学号", "性别", "班级", "语文", "数学", "英语", "总分", "操作"]) # 设置表头名称
# 将表格组件添加到主布局中
layout.addWidget(self.table_widget)
self.setStyleSheet("StudentInterface{background: white}") # 设置界面背景为白色
self.resize(1280, 760) # 设置窗口大小为 1280x760
def load_data(self): # 定义 load_data 方法,用于加载学生数据
# 使用假数据替换数据库查询
self.students = [
{"student_id": 1, "student_name": "张三", "student_number": "2024010101", "gender": 1, "class_name": "一年1班", "chinese_score": 85, "math_score": 90, "english_score": 88, "total_score": 260},
{"student_id": 2, "student_name": "李四", "student_number": "2024010102", "gender": 2, "class_name": "一年1班", "chinese_score": 92, "math_score": 88, "english_score": 95, "total_score": 260},
{"student_id": 3, "student_name": "王五", "student_number": "2024010103", "gender": 1, "class_name": "一年1班", "chinese_score": 78, "math_score": 82, "english_score": 80, "total_score": 260},
{"student_id": 4, "student_name": "赵六", "student_number": "2024010104", "gender": 2, "class_name": "一年1班", "chinese_score": 88, "math_score": 95, "english_score": 89, "total_score": 260},
{"student_id": 5, "student_name": "陈七", "student_number": "2024010105", "gender": 1, "class_name": "一年1班", "chinese_score": 90, "math_score": 91, "english_score": 93, "total_score": 260},
]
# 主程序入口
if __name__ == '__main__':
app = QApplication(sys.argv) # 创建应用程序实例
window = StudentInterface() # 创建 StudentInterface 窗口实例
window.show() # 显示窗口
sys.exit(app.exec()) # 进入应用程序主循环,并在退出时返回状态码
为了将数据展示在表格中,我们在student_interface.py文件中定义 populate_table 方法,将数据逐行添加到表格中。代码如下:
# student_interface.py 文件
import sys # 导入 sys 模块,用于处理系统相关的功能
from PyQt6.QtCore import Qt # 导入 Qt,用于设置对齐方式
# 从 PyQt6.QtWidgets 模块中导入 QWidget、QVBoxLayout、QHBoxLayout、QApplication 和 QHeaderView、QCheckBox、QTableWidgetItem
# 分别用于创建窗口部件、垂直布局、水平布局、应用程序、表格头部视图、复选框和表格项
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QApplication, QHeaderView, QCheckBox, QTableWidgetItem
# 从 qfluentwidgets 库中导入 CardWidget、PushButton、SearchLineEdit、TableWidget、setCustomStyleSheet
# 用于创建卡片样式的组件、按钮、搜索输入框、表格组件以及设置自定义样式
from qfluentwidgets import CardWidget, PushButton, SearchLineEdit, TableWidget, setCustomStyleSheet
# 导入自定义样式,用于“新增”和“批量删除”按钮
from utils.custom_style import ADD_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
# 定义 StudentInterface 类,继承自 QWidget
class StudentInterface(QWidget):
def __init__(self): # 初始化方法
super().__init__() # 调用父类 QWidget 的初始化方法
self.setObjectName("studentInterface") # 设置当前界面的对象名称
self.students = [] # 用于存储学生数据的列表
self.setup_ui() # 调用 setup_ui 方法,配置界面布局和组件
self.load_data() # 调用 load_data 方法,加载学生数据
def setup_ui(self): # 定义 setup_ui 方法,用于设置界面的布局和组件
layout = QVBoxLayout(self) # 创建垂直布局,并将其设置为当前窗口的主布局
# 顶部按钮组
card_widget = CardWidget(self) # 创建卡片样式的组件作为按钮组容器,并设置父组件为当前窗口
buttons_layout = QHBoxLayout(card_widget) # 创建水平布局,用于放置按钮,并将其设置为 card_widget 的布局
self.addButton = PushButton("新增", self) # 创建一个“新增”按钮,并将其设置为当前窗口的子组件
setCustomStyleSheet(self.addButton, ADD_BUTTON_STYLE, ADD_BUTTON_STYLE) # 应用自定义样式
# 创建搜索输入框
self.searchInput = SearchLineEdit(self) # 创建一个搜索输入框,并将其设置为当前窗口的子组件
self.searchInput.setPlaceholderText("搜索学生姓名或学号...") # 设置占位提示文字
self.searchInput.setFixedWidth(500) # 设置输入框固定宽度为 500
# 创建“批量删除”按钮并应用自定义样式
self.batchDeleteButton = PushButton("批量删除", self)
setCustomStyleSheet(self.batchDeleteButton, BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE)
# 将按钮和搜索框添加到按钮组的水平布局中
buttons_layout.addWidget(self.addButton) # 添加“新增”按钮
buttons_layout.addWidget(self.searchInput) # 添加搜索输入框
buttons_layout.addStretch(1) # 添加弹性空间,将按钮推向两端
buttons_layout.addWidget(self.batchDeleteButton) # 添加“批量删除”按钮
# 将按钮组的卡片组件添加到主布局中
layout.addWidget(card_widget)
# 表格组件(创建空表格,后续填充内容)
self.table_widget = TableWidget(self)
self.table_widget.setBorderVisible(True) # 设置表格边框可见
self.table_widget.setBorderRadius(8) # 设置表格圆角
self.table_widget.setWordWrap(False) # 禁用自动换行
# 设置表头填充模式和列数
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch) # 表头填充模式为 Stretch,使表头填满整个表格,并实现列宽自适应屏幕缩放的效果
self.table_widget.setColumnCount(11) # 设置表格列数为 11 列
self.table_widget.setHorizontalHeaderLabels(
["", "学生ID", "姓名", "学号", "性别", "班级", "语文", "数学", "英语", "总分", "操作"]) # 设置表头名称
# 将表格组件添加到主布局中
layout.addWidget(self.table_widget)
self.setStyleSheet("StudentInterface{background: white}") # 设置界面背景为白色
self.resize(1280, 760) # 设置窗口大小为 1280x760
def load_data(self): # 定义 load_data 方法,用于加载学生数据
# 使用假数据替换数据库查询
self.students = [
{"student_id": 1, "student_name": "张三", "student_number": "2024010101", "gender": 1, "class_name": "一年1班", "chinese_score": 85, "math_score": 90, "english_score": 88, "total_score": 260},
{"student_id": 2, "student_name": "李四", "student_number": "2024010102", "gender": 2, "class_name": "一年1班", "chinese_score": 92, "math_score": 88, "english_score": 95, "total_score": 260},
{"student_id": 3, "student_name": "王五", "student_number": "2024010103", "gender": 1, "class_name": "一年1班", "chinese_score": 78, "math_score": 82, "english_score": 80, "total_score": 260},
{"student_id": 4, "student_name": "赵六", "student_number": "2024010104", "gender": 2, "class_name": "一年1班", "chinese_score": 88, "math_score": 95, "english_score": 89, "total_score": 260},
{"student_id": 5, "student_name": "陈七", "student_number": "2024010105", "gender": 1, "class_name": "一年1班", "chinese_score": 90, "math_score": 91, "english_score": 93, "total_score": 260},
]
def populate_table(self): # 定义 populate_table 方法,用于填充表格数据
self.table_widget.setRowCount(len(self.students)) # 设置表格行数为学生数据的数量
for row, student_info in enumerate(self.students): # 遍历学生数据并设置每行的内容
self.setup_table_row(row, student_info) # 调用 setup_table_row 方法,设置每一行的数据
# 主程序入口
if __name__ == '__main__':
app = QApplication(sys.argv) # 创建应用程序实例
window = StudentInterface() # 创建 StudentInterface 窗口实例
window.show() # 显示窗口
sys.exit(app.exec()) # 进入应用程序主循环,并在退出时返回状态码
添加行数据
接下来我们在student_interface.py文件中定义 setup_table_row 方法中,为每一行添加数据。首先,在每行的第一列设置一个单选框,使用 PyQt6 中的 QCheckBox 元件,将其放置在单元格中。然后通过 setCellWidget 方法将单选框加入到指定的单元格中。代码如下:
checkbox = QCheckBox() # 创建复选框
self.table_widget.setCellWidget(row, 0, checkbox) # 将复选框添加到表格的第一列
接下来,逐个填充其他列的数据。为简化代码,通过一个 for 循环,将每列数据依次写入表格。在循环中,根据字段名称从 student_info 字典中获取数据,使用 QTableWidgetItem 创建表格项,并将项添加到相应的单元格中。需要注意的是,由于第一列已被单选框占用,因此数据从第二列开始填写。整个填充过程会根据数据的行数和列数自动遍历。代码如下:
# student_interface.py 文件
import sys # 导入 sys 模块,用于处理系统相关的功能
from PyQt6.QtCore import Qt # 导入 Qt,用于设置对齐方式
# 从 PyQt6.QtWidgets 模块中导入 QWidget、QVBoxLayout、QHBoxLayout、QApplication 和 QHeaderView、QCheckBox、QTableWidgetItem
# 分别用于创建窗口部件、垂直布局、水平布局、应用程序、表格头部视图、复选框和表格项
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QApplication, QHeaderView, QCheckBox, QTableWidgetItem
# 从 qfluentwidgets 库中导入 CardWidget、PushButton、SearchLineEdit、TableWidget、setCustomStyleSheet
# 用于创建卡片样式的组件、按钮、搜索输入框、表格组件以及设置自定义样式
from qfluentwidgets import CardWidget, PushButton, SearchLineEdit, TableWidget, setCustomStyleSheet
# 导入自定义样式,用于“新增”和“批量删除”按钮
from utils.custom_style import ADD_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
# 定义 StudentInterface 类,继承自 QWidget
class StudentInterface(QWidget):
def __init__(self): # 初始化方法
super().__init__() # 调用父类 QWidget 的初始化方法
self.setObjectName("studentInterface") # 设置当前界面的对象名称
self.students = [] # 用于存储学生数据的列表
self.setup_ui() # 调用 setup_ui 方法,配置界面布局和组件
self.load_data() # 调用 load_data 方法,加载学生数据
self.populate_table() # 调用 populate_table 方法,填充表格
def setup_ui(self): # 定义 setup_ui 方法,用于设置界面的布局和组件
layout = QVBoxLayout(self) # 创建垂直布局,并将其设置为当前窗口的主布局
# 顶部按钮组
card_widget = CardWidget(self) # 创建卡片样式的组件作为按钮组容器,并设置父组件为当前窗口
buttons_layout = QHBoxLayout(card_widget) # 创建水平布局,用于放置按钮,并将其设置为 card_widget 的布局
self.addButton = PushButton("新增", self) # 创建一个“新增”按钮,并将其设置为当前窗口的子组件
setCustomStyleSheet(self.addButton, ADD_BUTTON_STYLE, ADD_BUTTON_STYLE) # 应用自定义样式
# 创建搜索输入框
self.searchInput = SearchLineEdit(self) # 创建一个搜索输入框,并将其设置为当前窗口的子组件
self.searchInput.setPlaceholderText("搜索学生姓名或学号...") # 设置占位提示文字
self.searchInput.setFixedWidth(500) # 设置输入框固定宽度为 500
# 创建“批量删除”按钮并应用自定义样式
self.batchDeleteButton = PushButton("批量删除", self)
setCustomStyleSheet(self.batchDeleteButton, BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE)
# 将按钮和搜索框添加到按钮组的水平布局中
buttons_layout.addWidget(self.addButton) # 添加“新增”按钮
buttons_layout.addWidget(self.searchInput) # 添加搜索输入框
buttons_layout.addStretch(1) # 添加弹性空间,将按钮推向两端
buttons_layout.addWidget(self.batchDeleteButton) # 添加“批量删除”按钮
# 将按钮组的卡片组件添加到主布局中
layout.addWidget(card_widget)
# 表格组件(创建空表格,后续填充内容)
self.table_widget = TableWidget(self)
self.table_widget.setBorderVisible(True) # 设置表格边框可见
self.table_widget.setBorderRadius(8) # 设置表格圆角
self.table_widget.setWordWrap(False) # 禁用自动换行
# 设置表头填充模式和列数
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch) # 表头填充模式为 Stretch,使表头填满整个表格,并实现列宽自适应屏幕缩放的效果
self.table_widget.setColumnCount(11) # 设置表格列数为 11 列
self.table_widget.setHorizontalHeaderLabels(
["", "学生ID", "姓名", "学号", "性别", "班级", "语文", "数学", "英语", "总分", "操作"]) # 设置表头名称
# 将表格组件添加到主布局中
layout.addWidget(self.table_widget)
self.setStyleSheet("StudentInterface{background: white}") # 设置界面背景为白色
self.resize(1280, 760) # 设置窗口大小为 1280x760
def load_data(self): # 定义 load_data 方法,用于加载学生数据
# 使用假数据替换数据库查询
self.students = [
{"student_id": 1, "student_name": "张三", "student_number": "2024010101", "gender": 1, "class_name": "一年1班", "chinese_score": 85, "math_score": 90, "english_score": 88, "total_score": 260},
{"student_id": 2, "student_name": "李四", "student_number": "2024010102", "gender": 2, "class_name": "一年1班", "chinese_score": 92, "math_score": 88, "english_score": 95, "total_score": 260},
{"student_id": 3, "student_name": "王五", "student_number": "2024010103", "gender": 1, "class_name": "一年1班", "chinese_score": 78, "math_score": 82, "english_score": 80, "total_score": 260},
{"student_id": 4, "student_name": "赵六", "student_number": "2024010104", "gender": 2, "class_name": "一年1班", "chinese_score": 88, "math_score": 95, "english_score": 89, "total_score": 260},
{"student_id": 5, "student_name": "陈七", "student_number": "2024010105", "gender": 1, "class_name": "一年1班", "chinese_score": 90, "math_score": 91, "english_score": 93, "total_score": 260},
]
def populate_table(self): # 定义 populate_table 方法,用于填充表格数据
self.table_widget.setRowCount(len(self.students)) # 设置表格行数为学生数据的数量
for row, student_info in enumerate(self.students): # 遍历学生数据并设置每行的内容
self.setup_table_row(row, student_info) # 调用 setup_table_row 方法,设置每一行的数据
def setup_table_row(self, row, student_info): # 定义 setup_table_row 方法,用于设置表格行数据
checkbox = QCheckBox() # 创建复选框
self.table_widget.setCellWidget(row, 0, checkbox) # 将复选框添加到表格的第一列
# 遍历学生数据的各个字段并添加到表格中
for col, key in enumerate(['student_id', 'student_name', 'student_number', 'gender', 'class_name', 'chinese_score', 'math_score',
'english_score', 'total_score']):
value = student_info.get(key, '') # 获取对应字段的值
item = QTableWidgetItem(str(value)) # 创建表格项
self.table_widget.setItem(row, col + 1, item) # 将表格项添加到表格中对应的列
# 主程序入口
if __name__ == '__main__':
app = QApplication(sys.argv) # 创建应用程序实例
window = StudentInterface() # 创建 StudentInterface 窗口实例
window.show() # 显示窗口
sys.exit(app.exec()) # 进入应用程序主循环,并在退出时返回状态码
数据格式化显示
在数据填充过程中,我们可以对特定字段进行格式化处理。性别字段在数据库中以数值 1 和 2 表示,分别对应“男”和“女”。在展示时,我们可以添加一个条件判断,当字段为性别时,判断值为 1 时显示为“男”,为 2 时显示为“女”,否则显示为“未知”,并且把单元格文字居中显示,代码如下:
# student_interface.py 文件
import sys # 导入 sys 模块,用于处理系统相关的功能
from PyQt6.QtCore import Qt # 导入 Qt,用于设置对齐方式
# 从 PyQt6.QtWidgets 模块中导入 QWidget、QVBoxLayout、QHBoxLayout、QApplication 和 QHeaderView、QCheckBox、QTableWidgetItem
# 分别用于创建窗口部件、垂直布局、水平布局、应用程序、表格头部视图、复选框和表格项
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QApplication, QHeaderView, QCheckBox, QTableWidgetItem
# 从 qfluentwidgets 库中导入 CardWidget、PushButton、SearchLineEdit、TableWidget、setCustomStyleSheet
# 用于创建卡片样式的组件、按钮、搜索输入框、表格组件以及设置自定义样式
from qfluentwidgets import CardWidget, PushButton, SearchLineEdit, TableWidget, setCustomStyleSheet
# 导入自定义样式,用于“新增”和“批量删除”按钮
from utils.custom_style import ADD_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
# 定义 StudentInterface 类,继承自 QWidget
class StudentInterface(QWidget):
def __init__(self): # 初始化方法
super().__init__() # 调用父类 QWidget 的初始化方法
self.setObjectName("studentInterface") # 设置当前界面的对象名称
self.students = [] # 用于存储学生数据的列表
self.setup_ui() # 调用 setup_ui 方法,配置界面布局和组件
self.load_data() # 调用 load_data 方法,加载学生数据
self.populate_table() # 调用 populate_table 方法,填充表格
def setup_ui(self): # 定义 setup_ui 方法,用于设置界面的布局和组件
layout = QVBoxLayout(self) # 创建垂直布局,并将其设置为当前窗口的主布局
# 顶部按钮组
card_widget = CardWidget(self) # 创建卡片样式的组件作为按钮组容器,并设置父组件为当前窗口
buttons_layout = QHBoxLayout(card_widget) # 创建水平布局,用于放置按钮,并将其设置为 card_widget 的布局
self.addButton = PushButton("新增", self) # 创建一个“新增”按钮,并将其设置为当前窗口的子组件
setCustomStyleSheet(self.addButton, ADD_BUTTON_STYLE, ADD_BUTTON_STYLE) # 应用自定义样式
# 创建搜索输入框
self.searchInput = SearchLineEdit(self) # 创建一个搜索输入框,并将其设置为当前窗口的子组件
self.searchInput.setPlaceholderText("搜索学生姓名或学号...") # 设置占位提示文字
self.searchInput.setFixedWidth(500) # 设置输入框固定宽度为 500
# 创建“批量删除”按钮并应用自定义样式
self.batchDeleteButton = PushButton("批量删除", self)
setCustomStyleSheet(self.batchDeleteButton, BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE)
# 将按钮和搜索框添加到按钮组的水平布局中
buttons_layout.addWidget(self.addButton) # 添加“新增”按钮
buttons_layout.addWidget(self.searchInput) # 添加搜索输入框
buttons_layout.addStretch(1) # 添加弹性空间,将按钮推向两端
buttons_layout.addWidget(self.batchDeleteButton) # 添加“批量删除”按钮
# 将按钮组的卡片组件添加到主布局中
layout.addWidget(card_widget)
# 表格组件(创建空表格,后续填充内容)
self.table_widget = TableWidget(self)
self.table_widget.setBorderVisible(True) # 设置表格边框可见
self.table_widget.setBorderRadius(8) # 设置表格圆角
self.table_widget.setWordWrap(False) # 禁用自动换行
# 设置表头填充模式和列数
self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch) # 表头填充模式为 Stretch,使表头填满整个表格,并实现列宽自适应屏幕缩放的效果
self.table_widget.setColumnCount(11) # 设置表格列数为 11 列
self.table_widget.setHorizontalHeaderLabels(
["", "学生ID", "姓名", "学号", "性别", "班级", "语文", "数学", "英语", "总分", "操作"]) # 设置表头名称
# 将表格组件添加到主布局中
layout.addWidget(self.table_widget)
self.setStyleSheet("StudentInterface{background: white}") # 设置界面背景为白色
self.resize(1280, 760) # 设置窗口大小为 1280x760
def load_data(self): # 定义 load_data 方法,用于加载学生数据
# 使用假数据替换数据库查询
self.students = [
{"student_id": 1, "student_name": "张三", "student_number": "2024010101", "gender": 1, "class_name": "一年1班", "chinese_score": 85, "math_score": 90, "english_score": 88, "total_score": 260},
{"student_id": 2, "student_name": "李四", "student_number": "2024010102", "gender": 2, "class_name": "一年1班", "chinese_score": 92, "math_score": 88, "english_score": 95, "total_score": 260},
{"student_id": 3, "student_name": "王五", "student_number": "2024010103", "gender": 1, "class_name": "一年1班", "chinese_score": 78, "math_score": 82, "english_score": 80, "total_score": 260},
{"student_id": 4, "student_name": "赵六", "student_number": "2024010104", "gender": 2, "class_name": "一年1班", "chinese_score": 88, "math_score": 95, "english_score": 89, "total_score": 260},
{"student_id": 5, "student_name": "陈七", "student_number": "2024010105", "gender": 1, "class_name": "一年1班", "chinese_score": 90, "math_score": 91, "english_score": 93, "total_score": 260},
]
def populate_table(self): # 定义 populate_table 方法,用于填充表格数据
self.table_widget.setRowCount(len(self.students)) # 设置表格行数为学生数据的数量
for row, student_info in enumerate(self.students): # 遍历学生数据并设置每行的内容
self.setup_table_row(row, student_info) # 调用 setup_table_row 方法,设置每一行的数据
def setup_table_row(self, row, student_info): # 定义 setup_table_row 方法,用于设置表格行数据
checkbox = QCheckBox() # 创建复选框
self.table_widget.setCellWidget(row, 0, checkbox) # 将复选框添加到表格的第一列
# 遍历学生数据的各个字段并添加到表格中
for col, key in enumerate(['student_id', 'student_name', 'student_number', 'gender', 'class_name', 'chinese_score', 'math_score',
'english_score', 'total_score']):
value = student_info.get(key, '') # 获取对应字段的值
if key == 'gender': # 若字段为性别,进行性别的转换显示
value = '男' if value == 1 else '女' if value == 2 else '未知'
item = QTableWidgetItem(str(value)) # 创建表格项
item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) # 设置文本居中
self.table_widget.setItem(row, col + 1, item) # 将表格项添加到表格中对应的列
# 主程序入口
if __name__ == '__main__':
app = QApplication(sys.argv) # 创建应用程序实例
window = StudentInterface() # 创建 StudentInterface 窗口实例
window.show() # 显示窗口
sys.exit(app.exec()) # 进入应用程序主循环,并在退出时返回状态码
完成上述步骤后,调用 populate_table 方法即可在界面上展示表格的假数据。最终效果显示为每行第一列为单选框,后续列显示对应的字段内容,其中性别字段已正确转化为“男”或“女”,文字在单元格中居中显示,如下图所示:
领取专属 10元无门槛券
私享最新 技术干货