#include "CheckBoxHeaderView.h" CheckBoxHeaderView::CheckBoxHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget* parent) :QHeaderView(orientation, parent) { m_checkColIdx = checkColumnIndex; m_isChecked = false; } void CheckBoxHeaderView::setCheckStaus(bool isChecked) { m_isChecked = isChecked; this->updateSection(m_checkColIdx); } bool CheckBoxHeaderView::getCheckStaus() { return m_isChecked; } /// /// 绘制区域事件 /// /// 画笔 /// 区域 /// 索引 void CheckBoxHeaderView::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; option.rect = QRect((rect.right() - rect.left()) / 2 - width / 2 + rect.left() - 1, (rect.bottom() - rect.top()) / 2 - width / 2 + rect.top() - 1, width, width); if (m_isChecked) { option.state = QStyle::State_Enabled | QStyle::State_On; } else { option.state = QStyle::State_Enabled | QStyle::State_Off; } this->style()->drawControl(QStyle::CE_CheckBox, &option, painter); } } /// /// 鼠标按下事件 /// /// 事件 void CheckBoxHeaderView::mousePressEvent(QMouseEvent* event) { if (visualIndexAt(event->pos().x()) == m_checkColIdx) { if (m_isChecked) m_isChecked = false; else m_isChecked = true; this->updateSection(m_checkColIdx); emit checkStausChange(m_isChecked); } QHeaderView::mousePressEvent(event); }