效果图
源码
#ifndef CCHECKBOXMODEL_H
#define CCHECKBOXMODEL_H
#include <QAbstractTableModel>
#include <QStyledItemDelegate>
#include <QEvent>
#include <QHeaderView>
#include <QPainter>
class TableHeaderView :public QHeaderView
{
Q_OBJECT
public:
TableHeaderView(Qt::Orientation orientation, QWidget *parent);
~TableHeaderView();
protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
bool event(QEvent *e) Q_DECL_OVERRIDE;
void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
public slots:
void onStateChanged(int state);
signals:
void stateChanged(int state);
private:
bool m_bPressed;
bool m_bChecked;
bool m_bTristate;
bool m_bNoChange;
bool m_bMoving;
};
class CheckBoxDelegate :public QStyledItemDelegate
{
Q_OBJECT
public:
CheckBoxDelegate(QObject *parent);
~CheckBoxDelegate();
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
protected:
bool editorEvent(QEvent *event, QAbstractItemModel *model,
const QStyleOptionViewItem &option, const QModelIndex &index);
};
#endif
#include "ccheckboxmodel.h"
#include <QCheckBox>
#include <QApplication>
#include <QMouseEvent>
#include <qmessagebox.h>
#ifdef _MSC_VER
#pragma execution_character_set("utf-8")
#endif
#define CHECK_BOX_COLUMN 0
TableHeaderView::TableHeaderView(Qt::Orientation orientation, QWidget *parent)
: QHeaderView(orientation, parent),
m_bPressed(false),
m_bChecked(false),
m_bTristate(false),
m_bNoChange(false),
m_bMoving(false)
{
setSectionsClickable(true);
}
TableHeaderView::~TableHeaderView()
{
}
void TableHeaderView::onStateChanged(int state)
{
if (state == Qt::PartiallyChecked) {
m_bTristate = true;
m_bNoChange = true;
}
else {
m_bNoChange = false;
}
m_bChecked = (state != Qt::Unchecked);
update();
}
void TableHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
QHeaderView::paintSection(