Pyqt5——变色的表格
2024-10-21 06:35:20
需求:鼠标左键点击表格后,对应的单元格背景颜色发生变化。
实现:(1)使用Qt的model-view模式生成表格视图。
(2)重写表格的点击事件。
(3)设置表格的背景颜色。
正常情况下,当用户选中单元格之后单元格背景颜色变为蓝色,如下图所示:
如果觉得这样表格过于单调,那么我们就用鼠标为它涂上颜色。
代码块:
View部分。
class MyTableView(QTableView):
"""View"""
SelectedCellSignal = pyqtSignal(QModelIndex) def __init__(self):
super(MyTableView, self).__init__() def mousePressEvent(self, e):
"""重写鼠标点击事件。"""
if e.button() == Qt.RightButton:
return super().mousePressEvent(e) # :获取鼠标点击的索引
index = self.indexAt(e.pos())
return self.SelectedCellSignal.emit(index)
Model部分。
class MyTableModel(QAbstractTableModel):
"""Model"""
def __init__(self):
super(MyTableModel, self).__init__()
self._data = []
self._background_color = []
self._headers = ['序号', '姓名', '性别', '年龄'] self._generate_data() def _generate_data(self):
"""填充表格数据"""
name_list = ['张三', '李四', '王五', '王小二', '李美丽', '王二狗'] for id_num, name in enumerate(name_list):
self._data.append([str(id_num), name, '男', str(random.randint(20, 25))]) # :默认单元格颜色为白色
self._background_color.append([QColor(255, 255, 255) for i in range(4)]) def rowCount(self, parent=QModelIndex()):
"""返回行数量。"""
return len(self._data) def columnCount(self, parent=QModelIndex()):
"""返回列数量。"""
return len(self._headers) def headerData(self, section, orientation, role):
"""设置表格头"""
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self._headers[section] def data(self, index, role):
"""显示表格中的数据。"""
if not index.isValid() or not 0 <= index.row() < self.rowCount():
return QVariant() row = index.row()
col = index.column() if role == Qt.DisplayRole:
return self._data[row][col]
elif role == Qt.BackgroundColorRole:
return self._background_color[row][col]
elif role == Qt.TextAlignmentRole:
return Qt.AlignCenter return QVariant() def cellPaint(self, index, color):
"""给单元格填充颜色。"""
row = index.row()
col = index.column() self._background_color[row][col] = QColor(color)
self.layoutChanged.emit()
窗体绘制:
class ColorfulTable(QWidget):
def __init__(self):
super().__init__() self.setWindowTitle('变色的表格') self.tableView = MyTableView()
self.tableModel = MyTableModel()
self.tableView.setModel(self.tableModel) self.tableView.SelectedCellSignal.connect(self.selectedCell) layout = QHBoxLayout()
layout.addWidget(self.tableView)
self.setLayout(layout) def selectedCell(self, index):
"""鼠标点击事件槽函数。"""
# :生成颜色字符串形如:#FFFFFF
color = '#{}'.format(''.join([hex(random.randint(0, 256))[2:].rjust(2, '0') for i in range(3)]))
self.tableModel.cellPaint(index, color)
最新文章
- IIS7 经典模式和集成模式的区别(转载)
- web安全之sql注入原理
- MongoDB 语法使用小结
- asp.net中如何绑定combox下拉框数据(调用存储过程)
- C# 6 —— 属性
- EasyMock(官方资料整理)
- IC芯片
- JAVA_build_ant_Tstamp
- C#使用Xamarin开发可移植移动应用(1.入门与Xamarin.Forms页面),附源码
- 51NOD 1238 最小公倍数之和 V3 [杜教筛]
- Python基础:数据类型-字符串(7)
- SQLServer之FOREIGN KEY约束
- CentOS 7 的安装
- GCC链接的几个注意点
- rpm安装时出现循环依赖
- mac os 卸载android studio 从新安装遇到的一些问题
- MFC中打印对话框CPrintDialog类
- OAF开发中一些LOV相关技巧 (转)
- 通过cookie验证用户登录
- SDL结合QWidget的简单使用说明(2)
热门文章
- Codeforces Round #693 (Div. 3) G. Moving to the Capital (图,dp)
- hdu1011 Starship Troopers
- zoj3471 Most Powerful
- Codeforces Round #656 (Div. 3) B. Restore the Permutation by Merger (模拟)
- 牛客编程巅峰赛S1第3场 - 青铜&;白银 C.牛牛晾衣服(二分)
- linux内核编程入门--系统调用监控文件访问
- HDU 4675 GCD of Sequence(莫比乌斯反演 + 打表注意事项)题解
- python 编码问题随笔
- 免费在线 Linux Desktop 环境
- MDN Browser Compatibility Report 2020