在QTableView表头里面添加CheckBox 您所在的位置:网站首页 qttablewidget表头设置 在QTableView表头里面添加CheckBox

在QTableView表头里面添加CheckBox

2024-01-08 02:53| 来源: 网络整理| 查看: 265

在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); } }

 

posted on 2019-09-05 17:22  孤山独剑  阅读(2842)  评论(0)  编辑  收藏  举报



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有