在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