QT 表格操作
from PyQt5 import QtGui
from PyQt5.QtCore import QSize, Qt, QRect
from PyQt5.QtGui import QPalette, QColor, QBrush
from PyQt5.QtWidgets import QWidget, QTableWidget, QTableWidgetItem, QApplication, QHeaderView, QGridLayout, QPushButton
import sys
Datas = []
class Table(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.h_list = ["公司名称", "企业名称", "任务类型", "报表名称", "任务结果", "地区版本", "地区", "账套日期", "任务创建时间", "任务id"]
if not len(Datas):
self.v_list = ["1"]
else:
self.v_list = [str(i + 1) for i in range(len(Datas))]
self.current_hover = [0, 0]
self.resize(900, 800)
self.grid = QGridLayout()
self.add_btn()
self.cancel_btn()
self.cancel_select_btn()
self.insert_up_btn()
self.insert_down_btn()
self.setObjectName('表格')
self.table = QTableWidget(self)
self.set_col_width() # 自动设置表格列宽
self.set_col_color()
self.table.setMouseTracking(True) # 设置鼠标追踪
self.table.cellEntered.connect(self.set_col_hover) # 鼠标划过变色
self.table_main() # 设置表格表头
self.load_data()
self.grid.addWidget(self.table, 1, 0, 1, 5, Qt.AlignCenter)
self.setLayout(self.grid)
def load_data(self):
"""
加载数据
Returns:
"""
for key, data in enumerate(Datas):
self.table.setItem(key, 0, QTableWidgetItem(data['gsName']))
self.table.setItem(key, 1, QTableWidgetItem(data['qyName']))
self.table.setItem(key, 2, QTableWidgetItem(data['rwlxText']))
self.table.setItem(key, 3, QTableWidgetItem(""))
self.table.setItem(key, 4, QTableWidgetItem(data['statusErrMsg']))
self.table.setItem(key, 5, QTableWidgetItem(data['version']))
self.table.setItem(key, 6, QTableWidgetItem(data['xzqh']))
self.table.setItem(key, 7, QTableWidgetItem(data['createTime'][:7]))
self.table.setItem(key, 8, QTableWidgetItem(data['createTime']))
self.table.setItem(key, 9, QTableWidgetItem(data['strTaskId']))
def add_btn(self):
"""
添加行 按钮
Returns:
"""
btn = QPushButton("添加行")
btn.clicked.connect(self.add_row) # 设置表格行数
self.grid.addWidget(btn, 0, 0)
def cancel_btn(self):
"""
删除行 按钮
Returns:
"""
btn = QPushButton("删除行")
btn.clicked.connect(self.cancel_row) # 设置表格行数
self.grid.addWidget(btn, 0, 1)
def cancel_select_btn(self):
"""
删除行 按钮
Returns:
"""
btn = QPushButton("删除选中行")
btn.clicked.connect(self.cancel_select_row) # 设置表格行数
self.grid.addWidget(btn, 0, 2)
def add_row(self):
"""
在最后一行添加
Returns:
"""
row_count = self.table.rowCount()
if not row_count:
row_count = 0
self.table.setRowCount(row_count+1)
def cancel_row(self):
"""
删除最后一行
Returns:
"""
row_count = self.table.rowCount()
if not row_count:
row_count = 0
self.table.removeRow(row_count-1)
def cancel_select_row(self):
"""
删除选中行
Returns:
"""
row_select_row = self.table.currentIndex()
if not row_select_row:
return
self.table.removeRow(row_select_row.row())
self.v_list.pop(-1)
self.table.setVerticalHeaderLabels(self.v_list) # 重新刷新当前列名
def insert_up_btn(self):
"""
向上插入 按钮
Returns:
"""
btn = QPushButton("向上插入")
btn.clicked.connect(lambda: self.insert_row(e=True)) # 向上插入一行
self.grid.addWidget(btn, 0, 3)
def insert_down_btn(self):
"""
向下插入 按钮
Returns:
"""
btn = QPushButton("向下插入")
btn.clicked.connect(self.insert_row) # 向下插入一行
self.grid.addWidget(btn, 0, 4)
def insert_row(self, e=False):
"""
向 上/下 插入一行
Args:
e: 是否向上插入 默认 False 向下插入
Returns:
"""
max_row = self.table.rowCount() # 获取总共有多少列
row_select_row = self.table.currentIndex() # 当前列的索引
if not row_select_row:
return
if e:
self.table.insertRow(row_select_row.row()) # 向上插入 使用当前索引
else:
self.table.insertRow(row_select_row.row() + 1) # 向下插入需要索引加 1 向上插入 使用当前索引
self.v_list.append(str(max_row + 1))
self.table.setVerticalHeaderLabels(self.v_list) # 重新刷新当前列名
def table_main(self):
"""
设置表格表头
Returns:
"""
self.table.setObjectName('ha')
self.table.setHorizontalHeaderLabels(self.h_list)
self.table.setVerticalHeaderLabels(self.v_list)
def set_col_width(self):
"""
自动设置表格列宽 程序当前宽度 / 总列数
Returns:
"""
self.table.setSortingEnabled(True) # 默认为False
self.table.setColumnCount(len(self.h_list)) # 设置表格列数
self.table.setRowCount(len(self.v_list)) # 设置表格行数
print(111)
self.table.setFixedSize(QSize(self.size().width(), self.size().height() - 50)) # 设置表格宽高
# 方法一: 手动设置
# for i in range(len(self.h_list)):
# self.table.setColumnWidth(i, self.size().width() / len(self.h_list))
# 方法二: 自动设置
# self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 列自适应,(水平方向占满窗体)
# # self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) # 行自适应,(垂直方向占满窗体)
# self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
def set_col_color(self):
"""
设置隔行变色
Returns:
"""
# self.table.setPalette(QPalette(QColor(102, 220, 121))) # 自定义设置隔行显示的颜色 默认为灰色
self.table.setAlternatingRowColors(True) # 隔行变色设置
def set_col_hover(self, row, column):
"""
在有数据的情况下 鼠标悬停后整行变色
Args:
row: 悬停行
column: 悬停列
Returns:
"""
max_col = self.table.columnCount() # 获取总共有多少列
for i in range(max_col):
item = self.table.item(row, i)
if not item: # 检测到如果没有数据情况下 赋予空值
self.table.setItem(row, i, QTableWidgetItem(''))
old_item = self.table.item(self.current_hover[0], i)
if self.current_hover[0] != row:
if old_item:
old_item.setBackground(QBrush(QColor('white'))) # 悬停前一行设置白色
if item:
item.setBackground(QBrush(QColor('yellow'))) # 悬停行设置黄色
self.current_hover = [row, column]
def set_cell_hover(self, row, column):
"""
在有数据的情况下 鼠标悬停后单个单元格变色
Args:
row: 悬停行
column: 悬停列
Returns:
"""
item = self.table.item(row, column)
old_item = self.table.item(self.current_hover[0], self.current_hover[1])
if self.current_hover != [row, column]:
old_item.setBackground(QBrush(QColor('white')))
item.setBackground(QBrush(QColor('yellow')))
self.current_hover = [row, column]
def set_cross_hover(self, row, column):
"""
在有数据的情况下 鼠标悬停后当前单元格行列变色
Args:
row: 悬停行
column: 悬停列
Returns:
"""
max_row = self.table.rowCount() # 获取总共有多少行
max_col = self.table.columnCount() # 获取总共有多少列
for i in range(max_col):
if i == self.current_hover[1]:
continue
item = self.table.item(row, i)
old_item = self.table.item(self.current_hover[0], i)
if self.current_hover[0] != row:
if old_item:
old_item.setBackground(QBrush(QColor('white'))) # 悬停前一行设置白色
if item:
item.setBackground(QBrush(QColor('yellow'))) # 悬停行设置黄色
for i in range(max_row):
if i == self.current_hover[0]:
continue
item = self.table.item(i, column)
old_item = self.table.item(i, self.current_hover[1])
if self.current_hover != [row, column]:
if old_item:
old_item.setBackground(QBrush(QColor('white'))) # 悬停前一行设置白色
if item:
item.setBackground(QBrush(QColor('yellow'))) # 悬停行设置黄色
self.current_hover = [row, column]
if __name__ == '__main__':
app = QApplication(sys.argv)
table = Table()
table.show()
sys.exit(app.exec())
网友评论