1. 程式人生 > 其它 >Qt表格TableWidget新增複選框並居中

Qt表格TableWidget新增複選框並居中

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