在QTableView表头里面添加CheckBox
时间: 2023-09-13 18:10:14 浏览: 196
要在QTableView表头中添加CheckBox,需要实现自定义QHeaderView并重写其paintSection()和mousePressEvent()方法。
首先,在自定义的QHeaderView的构造函数中设置其为可以接收鼠标事件:
```python
class CheckBoxHeader(QtWidgets.QHeaderView):
def __init__(self, parent):
super().__init__(QtCore.Qt.Horizontal, parent)
self.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.setClickable(True)
self.setSortIndicatorShown(False)
```
然后,重写paintSection()方法,在其中绘制CheckBox:
```python
class CheckBoxHeader(QtWidgets.QHeaderView):
def paintSection(self, painter, rect, logicalIndex):
painter.save()
super().paintSection(painter, rect, logicalIndex)
if logicalIndex == 0:
option = QtWidgets.QStyleOptionButton()
option.rect = QtCore.QRect(10, 5, 20, 20)
option.state = QtWidgets.QStyle.State_Enabled | QtWidgets.QStyle.State_Active
if self.isChecked:
option.state |= QtWidgets.QStyle.State_On
else:
option.state |= QtWidgets.QStyle.State_Off
self.style().drawControl(QtWidgets.QStyle.CE_CheckBox, option, painter)
painter.restore()
```
最后,重写mousePressEvent()方法,在其中判断是否点击了CheckBox,并根据需要切换其状态:
```python
class CheckBoxHeader(QtWidgets.QHeaderView):
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
if self.logicalIndexAt(event.pos()) == 0:
self.isChecked = not self.isChecked
self.sectionClicked.emit(0)
self.viewport().update()
else:
super().mousePressEvent(event)
```
在使用QTableView时,将其表头设置为自定义的CheckBoxHeader即可:
```python
tableView = QtWidgets.QTableView()
header = CheckBoxHeader(tableView)
tableView.setHorizontalHeader(header)
```
阅读全文