Qt Qtablewidget 标题 QHeaderView 增加可选框 QcheckBox
创建自定义QHeaderView
#pragma once
#include <QObject>
#include <QHeaderView>
#include <QPainter>
#include <QMouseEvent>
class SSHeaderView : public QHeaderView
{
Q_OBJECT
private:
bool isChecked;
int m_checkColIdx;
public:
SSHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget * parent = 0) :
QHeaderView(orientation, parent) {
m_checkColIdx = checkColumnIndex;
isChecked = false;
}
signals:
void checkStausChange(bool);
protected:
void 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, 3, 21, 21);
if (isChecked)
option.state = QStyle::State_On;
else
option.state = QStyle::State_Off;
this->style()->drawControl(QStyle::CE_CheckBox, &option, painter);
}
}
void mousePressEvent(QMouseEvent *event) {
if (visualIndexAt(event->pos().x()) == m_checkColIdx) {
isChecked = !isChecked;
this->updateSection(m_checkColIdx);
emit checkStausChange(isChecked);
}
QHeaderView::mousePressEvent(event);
}
};
使用:
SSHeaderView *m_checkHeader = new SSHeaderView(0, Qt::Horizontal, qtableWidget);
qtableWidget->setHorizontalHeader(m_checkHeader);
connect(m_checkHeader, &SSHeaderView::checkStausChange, [=](bool check) {
qDebug() << "is:" << check;
});
最终效果: