Pyqt5——变色的表格
需求:鼠标左键点击表格后,对应的单元格背景颜色发生变化。
实现:(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)
Pyqt5——变色的表格的更多相关文章
- css选择器,用来处理隔行变色的表格
CSS3 :nth-last-child() 选择器,可以用来处理隔行变色的表格,详情请参考网上资料.
- css3表格隔行变色和表格选中变颜色代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- [ PyQt入门教程 ] PyQt5中数据表格控件QTableWidget使用方法
如果你想让你开发的PyQt5工具展示的数据显得整齐.美观.好看,显得符合你的气质,可以考虑使用QTableWidget控件.之前一直使用的是textBrowser文本框控件,数据展示还是不太美观.其中 ...
- Javascript:DOM表格操作
需求说明: /* *需求说明: *获取元素:tBodies,tHead,tFoot,rows,cells *表格的创建 *数据添加 *隔行变色 *删除操作,剩余表格重新计算,实现隔行变色 */ HTM ...
- Jquery表单与表格的运用
1,表单的应用: a. 单行文本框的应用 多行文本框的应用 b.复选框的框的应用 c.下拉框的应用 d.表单验证 2,表格的应用: a. 表格变色 b.表格展开关闭 d.表格内容筛选 3,多行文本框 ...
- (8)css表格
用css设置表格样式 *<table></table> 标签定义 HTML 表格. * tr 元素定义表格的行:th 元素定义表格的表头:td 元素定义表格中的单元格:capt ...
- 测开之路一百零八:bootstrap表格
引入bootstrap和jquery 普通表格 html自带的边框线 bootstrap表格属性 bootstrap表格 边框线 鼠标经过变色 压缩表格,减小密度 自适应屏幕 隔行突出(变色) 表格里 ...
- BootStrap_02之全局样式及组件
1.BootStrap指定的四种屏幕尺寸: ①超大PC屏幕--lg(large):w>=1200px: ②中等PC屏幕--md(medium):1200px>w>=992px: ③P ...
- Boostrap全局CSS样式
1.Bootstrap提供的CSS Reset * { box-sizing: border-box; } body { font ...; color: #333; background: ...; ...
随机推荐
- HDU5213 Lucky【容斥+莫队】
HDU5213 Lucky 题意: 给出\(N\)个数和\(k\),有\(m\)次询问,每次询问区间\([L1,R1]\)和区间\([L2,R2]\)中分别取一个数能相加得到\(k\)的方案数 题解: ...
- HDOJ 1848(SG函数)
对于SG函数来说,sg[y]=x的意义为,x与y的输赢状态是相同的 sg[y]=mex(y)的定义与n.p点的定义是相同的 #include<iostream>#include<cs ...
- GCD HDU - 1695 容斥原理(复杂度低的版本)
题意: 让你从区间[a,b]里面找一个数x,在区间[c,d]里面找一个数y.题目上已经设定a=b=1了.问你能找到多少对GCD(x,y)=k.x=5,y=7和y=5,x=7是同一对 题解: 弄了半天才 ...
- Codeforces Round #641 (Div. 2) D. Orac and Medians (贪心)
题意:有一个长度为\(n\)的数组,问能否通过多次使某个区间的所有元素变成这个区间的中位数,来使整个数组变成题目所给定的\(k\). 题解:首先这个\(k\)一定要在数组中存在,然后我们对中位数进行考 ...
- CF1474-A. Puzzle From the Future
CF1474-A. Puzzle From the Future 题意: 有两个由\(0,1\)组成的.长度相等字符串\(a, b\),两个字符串按位相加得到一个新的字符串\(s\),对\(s\)取\ ...
- kubeadm---高可用安装
1.修改主机名 如何使用hostnamectl set-hostname name来为每台主机设置不同的机器名 #hostnamectl set-hostname k8s-master01 或者使用以 ...
- Java之大数相加
之前参加某公司笔试,机试题目是大数相加,两大数是字符串形式,求和. 当时讨巧用的是BigDecimal类,但是发迷糊了,以为b1.add(b2)后,和就加到b1上了,结果一直输出不对. 其实应该是这样 ...
- 牛客多校第三场J LRU management(双向链表)题解
题意: 给一个长度为\(m\)的队列,现给定以下操作: \(opt=0\),插入一个串,如果不在队里直接插入栈尾,如果超出\(m\)删队首:在队里就拿出来重新放到队尾,返回\(v\)值. \(opt= ...
- surge & free online docs website service
surge & free online docs website service surge 自定义域的域名 https://surge.sh/help/adding-a-custom-dom ...
- npm version ^ meaning
npm version ^ meaning ^ 更新版 https://docs.npmjs.com/cli/v6/commands/npm-version https://github.com/ge ...