在 Qt 框架中,要在 QTableWidget
的表头中添加复选框,可以通过继承 QHeaderView
并重写 paintSection
方法来实现。
如下介绍一种继承 QHeaderView的方法分别实现
QTableWidget中添加复选框,可全选/全不选/部分选。
效果:
主要原理:
-
void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
:- 这是一个重写的函数,用于绘制指定
logicalIndex
的表头部分。 - 首先,它调用了基类
QHeaderView
的paintSection
方法,以绘制默认的表头样式。 - 然后,它在特定的
logicalIndex
(通常是某一列)处绘制一个复选框。 - 复选框的位置和样式由
option.rect
、option.palette
和option.state
等属性控制。 - 如果
isChecked
为真,复选框处于选中状态;否则,处于未选中状态。
- 这是一个重写的函数,用于绘制指定
-
void HeaderView::mousePressEvent(QMouseEvent *event)
:- 这是另一个重写的函数,用于处理鼠标按下事件。
- 如果鼠标点击的位置对应于复选框所在的列(
m_checkColIdx
),则切换isChecked
的状态。 - 然后,通过调用
updateSection(m_checkColIdx)
更新表头的显示。 - 最后,发出信号
checkStausChange(isChecked)
,通知其他部分复选框状态的变化。
关键代码:
void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const {
painter->save();
QHeaderView::paintSection(painter, rect, logicalIndex);
painter->restore();
if (logicalIndex == m_checkColIdx) {
QStyleOptionButton option;
int width = 10;
for(int i=0; i<logicalIndex; ++i){
width += sectionSize( i );}
option.rect = QRect(3, 5, 21, 21);
QPalette palette = option.palette;
palette.setColor(QPalette::ButtonText, Qt::black); // 设置按钮文字颜色为黑色
option.palette = palette;
if (isChecked)
option.state = QStyle::State_On;
else
option.state = QStyle::State_Off;
this->style()->drawControl(QStyle::CE_CheckBox, &option, painter);
}
}
void HeaderView::mousePressEvent(QMouseEvent *event) {
if (visualIndexAt(event->pos().x()) == m_checkColIdx) {
isChecked = !isChecked;
this->updateSection(m_checkColIdx);
emit checkStausChange(isChecked);
}
QHeaderView::mousePressEvent(event);
}