QTableWidget添加單選框分為表頭添加單選框和表格中添加單選框,下面分別進行討論:
QTableWidget表格中添加單選框(並且讓單選框居中)
//設置操作框並設置為居中 QWidget *widget = new QWidget; QHBoxLayout *layout = new QHBoxLayout; QCheckBox *box = new QCheckBox; layout->addWidget(box); layout->setMargin(0); layout->setAlignment(box, Qt::AlignCenter); widget->setLayout(layout); table->setCellWidget(row, column, widget);
表頭添加單選框需要繼承QCheckBoxHeaderView類重寫部分內容才可以,下面是示例代碼:
#pragma once #include <QtGui> #include <QHeaderView> #include <QStyleOptionButton> #include <QStyle> class CCheckBoxHeaderView : public QHeaderView { Q_OBJECT public: CCheckBoxHeaderView(int checkColumnIndex,Qt::Orientation orientation,QWidget * parent = 0); void setCheckStaus(bool isChecked); bool getCheckStaus(); signals: void checkStausChange(bool); protected: void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const; void mousePressEvent(QMouseEvent *event); private: bool m_isChecked; int m_checkColIdx; };
#include "CCheckBoxHeaderView.h" CCheckBoxHeaderView::CCheckBoxHeaderView(int checkColumnIndex,Qt::Orientation orientation,QWidget * parent) :QHeaderView(orientation, parent) { m_checkColIdx = checkColumnIndex; m_isChecked = false; } void CCheckBoxHeaderView::setCheckStaus(bool isChecked) { m_isChecked = isChecked; this->updateSection(m_checkColIdx); } bool CCheckBoxHeaderView::getCheckStaus() { return m_isChecked; } void CCheckBoxHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const { painter->save(); QHeaderView::paintSection(painter, rect, logicalIndex); painter->restore(); if (logicalIndex == m_checkColIdx) { QStyleOptionButton option; int width = 10; for (int i = 0; i < logicalIndex; ++i) width += sectionSize(i); option.rect = QRect(5, 5, 21, 21); if (m_isChecked) option.state = QStyle::State_On; else option.state = QStyle::State_Off; // this->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter); this->style()->drawControl(QStyle::CE_CheckBox, &option, painter); } } void CCheckBoxHeaderView::mousePressEvent(QMouseEvent *event) { if (visualIndexAt(event->pos().x()) == m_checkColIdx) { if (m_isChecked) m_isChecked = false; else m_isChecked = true; this->updateSection(m_checkColIdx); emit checkStausChange(m_isChecked); } QHeaderView::mousePressEvent(event); }
最后在類中還需要添加表頭並設置對應槽函數:
//設置表頭全選框 CCheckBoxHeaderView *myHeader = new CCheckBoxHeaderView(0, Qt::Horizontal, ui.tableWidget); ui.tableWidget->setHorizontalHeader(myHeader); //點擊全選框后 connect(myHeader, &CCheckBoxHeaderView::checkStausChange, [&](bool flag) { Qt::CheckState state = (flag ? Qt::Checked : Qt::Unchecked); for (int index = 0;index < ui.tableWidget->rowCount();index++) { QWidget *widget = (QWidget *)ui.tableWidget->cellWidget(index, 0); QCheckBox *ckb = (QCheckBox *)widget->children().at(1); ckb->setCheckState(state); } });
最后樣式如下圖所示: