QHeaderView设置控件

之前有个模块需要在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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值