QTableView表頭新增QCheckBox複選框
阿新 • • 發佈:2020-12-14
說明
表格QTableView表頭新增複選框,實現全選/不選功能,實現方法:繼承QHeaderView,通過重寫paintSection方法實現,效果圖如下:
程式碼
.h
class CheckBoxHeader : public QHeaderView { Q_OBJECT public: CheckBoxHeader(Qt::Orientation orientation, QWidget* parent = 0); bool isChecked() const { return isChecked_; } void setIsChecked(bool val); signals: void checkBoxClicked(bool state); protected: void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const; void mousePressEvent(QMouseEvent* event); private: bool isChecked_; void redrawCheckBox(); };
.cpp
#include "CheckBoxHeader.h" CheckBoxHeader::CheckBoxHeader(Qt::Orientation orientation, QWidget* parent /*= 0*/) : QHeaderView(orientation, parent) { isChecked_ = true; } void CheckBoxHeader::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const { painter->save(); QHeaderView::paintSection(painter, rect, logicalIndex); painter->restore(); if (logicalIndex == 0) { QStyleOptionButton option; option.rect = QRect(1,3,20,20); option.state = QStyle::State_Enabled | QStyle::State_Active; if (isChecked_) option.state |= QStyle::State_On; else option.state |= QStyle::State_Off; option.state |= QStyle::State_Off; style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter); } } void CheckBoxHeader::mousePressEvent(QMouseEvent* event) { setIsChecked(!isChecked()); emit checkBoxClicked(isChecked()); } void CheckBoxHeader::redrawCheckBox() { viewport()->update(); } void CheckBoxHeader::setIsChecked(bool val) { if (isChecked_ != val) { isChecked_ = val; redrawCheckBox(); } }
usage
CheckBoxHeader* header = new CheckBoxHeader(Qt::Horizontal, &table);
table.setHorizontalHeader(header);
// 訊號
//connect(header, &CheckBoxHeader::checkBoxClicked, this, &MyForm::on_header_checkBoxClicked);