在QTableView表头里面添加CheckBox


自定义表头,并实现在第0列添加checkbox,复选框居中显示,点击表头设置checkbox状态

class HeaderViewPrivate : public QHeaderView
{
    Q_OBJECT
public:
    explicit HeaderViewPrivate(Qt::Orientation orientation, QWidget * parent = 0)
        : QHeaderView(orientation, parent) {
        m_cbx = new QCheckBox(this);
        m_cbx->setVisible(true);
        setSectionsClickable(true);//如果不加这行代码不会触发点击事件
        connect(this,SIGNAL(sectionClicked(int)),this, SLOT(onHeaderClicked(int)));
    }
protected:
    void updateGeometries()
    {
        int width=this->sectionSize(0);
        QRect rc(sectionPosition(0),this->rect().top(),width,this->rect().height());
        QRect rc1=m_cbx->rect();
        m_cbx->move(rc.left()+(rc.width()-rc1.width())/2, rc.top()+(rc.height()-rc1.height())/2);
    }
public slots:
    void onHeaderClicked(int nIndex)
    {
        if(nIndex==0)
        {
           m_cbx->setChecked(!m_cbx->isChecked());
        }
    }
private:
    QCheckBox *m_cbx;
};

 

//可添加checkbox的行表头,
class HeaderView : public QHeaderView
{
    Q_OBJECT
public:
    HeaderView(QWidget* parent = 0,int nAddCheckBoxColumn=0);
protected:
    void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const override;
public slots:
    void onHeaderClicked(int nIndex)
    {
        if(nIndex==0)
        {
            m_bChecked=!m_bChecked;
            this->repaint();
            emit columnCheck(0,m_bChecked);
        }
    }
Q_SIGNALS:
    void columnCheck(int logicalIndex, bool bChecked);
private:
    int m_nAddCheckBoxColumn;
    bool m_bChecked=false;
};

HeaderView::HeaderView(QWidget*  parent,int nAddCheckBoxColumn)
    : QHeaderView(Qt::Horizontal, parent)
{
    setSectionsClickable(true);//如果不加这行代码不会触发点击事件
    connect(this,SIGNAL(sectionClicked(int)),this, SLOT(onHeaderClicked(int)));
    m_nAddCheckBoxColumn=nAddCheckBoxColumn;
}

void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);
    painter->restore();

    if(logicalIndex == m_nAddCheckBoxColumn)
    {
        QStyleOptionButton checkBoxStyle;
        checkBoxStyle.state = m_bChecked ? QStyle::State_On : QStyle::State_Off;
        checkBoxStyle.state |= QStyle::State_Enabled;
        checkBoxStyle.iconSize = QSize(20, 20);
        QRect rc(rect.left()+(rect.width()-20)/2,rect.top()+(rect.height()-20)/2,20,20);
        checkBoxStyle.rect =rc;
        QCheckBox checkBox;
        QApplication::style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &checkBoxStyle, painter, &checkBox);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM