之前有个模块需要在QHeaderView上设置CheckBox,当时在网上查到的方法都是在paintSection函数里面用图片绘制,后来同事分享了一种直接new一个控件的方法,在此记录。
customheaderview.h
#include <QHeaderView>
#include <QComboBox>
#include <QCheckBox>
#include <QLineEdit>
class CustomHeaderView : public QHeaderView
{
Q_OBJECT
public:
CustomHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr);
QSize sizeHint() const;
protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const:
private:
QComboBox *m_pComboBox;
QCheckBox *m_pCheckBox;
QLineEdit *m_pLineEdit;
}
customheaderview.cpp
#include "customheaderview.h"
CustomHeaderView::CustomHeaderView(Qt::Orientation orientation, QWidget)
:QHeaderView(orientation, parent), m_pComboBox(new QComboBox(this))
, m_pCheckBox(new QCheckBox(this)), m_pLineEdit(new QLineEdit(this))
{
m_pComboBox->addItem("111");
m_pComboBox->addItem("222");
m_pComboBox->addItem("333");
}
QSize CustomHeaderView::sizeHint() const
{
QSize size = QHeaderView::sizeHint();
return size;
}
void CustomHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
QHeaderView::paintSection(painter, rect, logicalIndex);
if (0 == logicalIndex)
{
m_pCheckBox->setGeometry(rect);
m_pCheckBox->show();
}
else if (1 == logicalIndex)
{
m_pComboBox->setGeometry(rect);
m_pComboBox->show();
}
else if (2 == logicalIndex)
{
m_pLineEdit->setGeometry(rect);
m_pLineEdit->show();
}
}
具体使用
ui->tableWidget->setColumnCount(3);
CustomHeaderView *pView = new CustomHeaderView(Qt::horizontal, ui->tableWidget);
ui->tableWidget->setHorizontalHeader(pView);