效果
关键逻辑
重写表格的水平HeaderView,在表头中加入checkBox组件
#ifndef QCHECKBOXHEADERVIEW_H
#define QCHECKBOXHEADERVIEW_H
#include <QCheckBox>
#include <QComboBox>
#include <QHeaderView>
#include <QMap>
class CheckBoxHeaderView : public QHeaderView
{
Q_OBJECT
public:
CheckBoxHeaderView(QMap<int, QString> mapCheckBox, Qt::Orientation orientation, QWidget * parent = 0);
protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
private:
QMap<int, QCheckBox*> m_mapCheckBox;
};
#endif // QCHECKBOXHEADERVIEW_H
#include "QCheckBoxHeaderView.h"
CheckBoxHeaderView::CheckBoxHeaderView(QMap<int, QString> mapCheckBox, Qt::Orientation orientation, QWidget* parent)
: QHeaderView(orientation, parent)
{
for (auto it = mapCheckBox.begin(); it != mapCheckBox.end(); it++)
{
QCheckBox* checkBox = new QCheckBox(it.value(), this);
m_mapCheckBox.insert(it.key(), checkBox);
}
setMinimumHeight(40);
}
void CheckBoxHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
auto it = m_mapCheckBox.find(logicalIndex);
if (it == m_mapCheckBox.end())
{
QHeaderView::paintSection(painter, rect, logicalIndex);
return;
}
QCheckBox* checkBox = static_cast<QCheckBox*>(it.value());
if (checkBox != nullptr)
{
// 设置居中
QSize sizeCheckBox = checkBox->size();
QRect rcCheckBox;
rcCheckBox.setLeft((rect.right() - rect.left()) / 2 - sizeCheckBox.width() / 2 + rect.left());
rcCheckBox.setTop((rect.bottom() - rect.top()) / 2 - sizeCheckBox.height() / 2 + rect.top());
rcCheckBox.setRight(rcCheckBox.left() + sizeCheckBox.width() - 1);
rcCheckBox.setBottom(rcCheckBox.top() + sizeCheckBox.height() - 1);
checkBox->setGeometry(rcCheckBox);
}
}
#ifndef QTABLEWIDGETEX_H
#define QTABLEWIDGETEX_H
#include "QCheckBoxHeaderView.h"
#include <QTableWidget>
class QTableWidgetEx : public QTableWidget
{
Q_OBJECT
public:
QTableWidgetEx(QWidget *parent = nullptr);
// 设置表头复选框
void SetHeaderCheckBox(QMap<int, QString> mapCheckBox);
private:
};
#endif // QTABLEWIDGETEX_H
#include "QTableWidgetEx.h"
//需要添加的代码,防止中文出现乱码
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
QTableWidgetEx::QTableWidgetEx(QWidget *parent):QTableWidget(parent)
{
this->setAlternatingRowColors(true);
this->setColumnCount(3);
this->setSelectionMode(QAbstractItemView::SingleSelection);
this->setEditTriggers(QAbstractItemView::NoEditTriggers);
this->setSelectionBehavior(QAbstractItemView::SelectRows);
}
void QTableWidgetEx::SetHeaderCheckBox(QMap<int, QString> mapCheckBox)
{
CheckBoxHeaderView* m_checkBoxHeaderView = new CheckBoxHeaderView(mapCheckBox, Qt::Horizontal, this);
this->setHorizontalHeader(m_checkBoxHeaderView);
}