需求:鼠标左键点击表格后,对应的单元格背景颜色发生变化。

  实现:(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)

最新文章

  1. IIS7 经典模式和集成模式的区别(转载)
  2. web安全之sql注入原理
  3. MongoDB 语法使用小结
  4. asp.net中如何绑定combox下拉框数据(调用存储过程)
  5. C# 6 —— 属性
  6. EasyMock(官方资料整理)
  7. IC芯片
  8. JAVA_build_ant_Tstamp
  9. C#使用Xamarin开发可移植移动应用(1.入门与Xamarin.Forms页面),附源码
  10. 51NOD 1238 最小公倍数之和 V3 [杜教筛]
  11. Python基础:数据类型-字符串(7)
  12. SQLServer之FOREIGN KEY约束
  13. CentOS 7 的安装
  14. GCC链接的几个注意点
  15. rpm安装时出现循环依赖
  16. mac os 卸载android studio 从新安装遇到的一些问题
  17. MFC中打印对话框CPrintDialog类
  18. OAF开发中一些LOV相关技巧 (转)
  19. 通过cookie验证用户登录
  20. SDL结合QWidget的简单使用说明(2)

热门文章

  1. Codeforces Round #693 (Div. 3) G. Moving to the Capital (图,dp)
  2. hdu1011 Starship Troopers
  3. zoj3471 Most Powerful
  4. Codeforces Round #656 (Div. 3) B. Restore the Permutation by Merger (模拟)
  5. 牛客编程巅峰赛S1第3场 - 青铜&amp;白银 C.牛牛晾衣服(二分)
  6. linux内核编程入门--系统调用监控文件访问
  7. HDU 4675 GCD of Sequence(莫比乌斯反演 + 打表注意事项)题解
  8. python 编码问题随笔
  9. 免费在线 Linux Desktop 环境
  10. MDN Browser Compatibility Report 2020