#include "myheaderviewer.h"
#include<QPainter>
#include<QMouseEvent>
void MyHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
QHeaderView::paintSection(painter, rect, logicalIndex); //父类继承否则表头默认部分失效
painter->restore();
if (logicalIndex == 1) //表头第一列
{
//绘制大小,根据类成员triState1 状态来改变复选框的状态
QStyleOptionButton option;
option.initFrom(this);
option.rect = QRect(rect.x()/* + 10*/, rect.y() + 10, 18, 18);
option.features = QStyleOptionButton::None;
if (triState1 == Qt::Checked)
option.state |= QStyle::State_On;
else if (triState1 == Qt::PartiallyChecked)
option.state |= QStyle::State_NoChange;
else
option.state |= QStyle::State_Off;
style()->drawControl(QStyle::CE_CheckBox, &option, painter/*, checkBox*/);
}
}
//通过事件点击改变复选框的状态
void MyHeaderView::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton) { //判断鼠标左键
if (logicalIndexAt(event->pos()) == 1) { 判断序列号第一个的位置
switch (triState1) {
case Qt::Unchecked:
triState1 = Qt::Checked;
break;
case Qt::Checked:
triState1 = Qt::Unchecked;
break;
}
// updateSection(1);
}
emit checkBoxChangedIndex(logicalIndexAt(event->pos())); //点击复选框并且出发对外信号
}
QHeaderView::mousePressEvent(event);
}
QT重写表头之表头绘制复选框并且增加鼠标点击事件
于 2024-02-23 00:22:04 首次发布