Qt TableWidget添加复选框并居中
效果图如下,其中分为表头和表格复选框实现。
表头添加复选框并居中
思路:新建一个表头类继承QHeaderView类,重写paintSection方法,根据原型实现。
核心代码:
void CHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
QHeaderView::paintSection(painter, rect, logicalIndex);
painter->restore();
if (0 == logicalIndex)
{
QStyleOptionButton option;
QPixmap pix;
if (m_CheckedState == Qt::Checked)
{
//图片需要在资源里添加
pix.load(":/Img/boxChecked.png");//选中
option.state = QStyle::State_On;
}
else if (m_CheckedState == Qt::Unchecked)
{
pix.load(":/Img/boxUnchecked.png");//正常
option.state = QStyle::State_Off;
}
else if (m_CheckedState == Qt::PartiallyChecked)
{
pix.load(":/Img/boxPartiallyChecked.png");
}
style()->drawItemPixmap(painter, rect, Qt::AlignCenter, pix);
}
}
重写mousePressEvent方法,当点击复选框后对其进行刷新,并且发送当前复选框状态信号
void CHeaderView::mousePressEvent(QMouseEvent *event)
{
if(logicalIndexAt(event->pos()) == 0)
{
m_bIsChecked = !m_bIsChecked;
updateSection(0);//刷新表头第一列
emit headBoxIsChecked(m_bIsChecked);
}
else
{
QHeaderView::mousePressEvent(event);
}
}
创建槽函数 setCheckBoxState,设置更新表头复选框三种状态
void CHeaderView::setCheckBoxState(int state)
{
if (state == Qt::Checked)
{
m_CheckedState = Qt::Checked;
m_bIsChecked = true;
}
else if (state == Qt::Unchecked)
{
m_CheckedState = Qt::Unchecked;
m_bIsChecked = false;
}
else
{
m_CheckedState = Qt::PartiallyChecked;
m_bIsChecked = false;
}
updateSection(0);
}
表格复选框添加
复选框居中需要对其添加布局居中,最后将布局后的元素放入表格中
QWidget *widget = new QWidget();
QHBoxLayout *layout = new QHBoxLayout();
QCheckBox *checkBox = new QCheckBox;
checkBox->setObjectName(QString("%1_%2").arg(s32Row).arg(0));
checkBox->setStyleSheet("QCheckBox::indicator:unchecked {image: url(:/Img/boxUnchecked.png);}"
"QCheckBox::indicator:checked {image: url(:/Img/boxChecked.png);}"
".QCheckBox{margin-left:7px;}");
layout->addWidget(checkBox, 0, Qt::AlignCenter);
layout->setMargin(0);
widget->setLayout(layout);
//信号连接,当复选框状态改变后在SlotCheckBoxStateChange槽函数中做响应业务逻辑处理
connect(checkBox, &QCheckBox::stateChanged, this, &CConsult::SlotCheckBoxStateChange);
ui->table->setCellWidget(s32Row, 0, widget);