QT_qtablewidget表头添加复选框QHeaderView

        在 Qt 框架中,要在 QTableWidget的表头中添加复选框,可以通过继承 QHeaderView 并重写 paintSection 方法来实现。

        如下介绍一种继承 QHeaderView的方法分别实现QTableWidget中添加复选框,可全选/全不选/部分选。

效果:

主要原理:

  1. void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const

    • 这是一个重写的函数,用于绘制指定 logicalIndex 的表头部分。
    • 首先,它调用了基类 QHeaderView 的 paintSection 方法,以绘制默认的表头样式。
    • 然后,它在特定的 logicalIndex(通常是某一列)处绘制一个复选框。
    • 复选框的位置和样式由 option.rectoption.palette 和 option.state 等属性控制。
    • 如果 isChecked 为真,复选框处于选中状态;否则,处于未选中状态。
  2. void HeaderView::mousePressEvent(QMouseEvent *event)

    • 这是另一个重写的函数,用于处理鼠标按下事件。
    • 如果鼠标点击的位置对应于复选框所在的列(m_checkColIdx),则切换 isChecked 的状态。
    • 然后,通过调用 updateSection(m_checkColIdx) 更新表头的显示。
    • 最后,发出信号 checkStausChange(isChecked),通知其他部分复选框状态的变化。

关键代码:

void HeaderView::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(3, 5, 21, 21);
            QPalette palette = option.palette;
        palette.setColor(QPalette::ButtonText, Qt::black); // 设置按钮文字颜色为黑色
        option.palette = palette;
        if (isChecked)
            option.state = QStyle::State_On;
        else
            option.state = QStyle::State_Off;

    this->style()->drawControl(QStyle::CE_CheckBox, &option, painter);
    }
}

void HeaderView::mousePressEvent(QMouseEvent *event) {
    if (visualIndexAt(event->pos().x()) == m_checkColIdx) {
        isChecked = !isChecked;
        this->updateSection(m_checkColIdx);
        emit checkStausChange(isChecked);
    }
    QHeaderView::mousePressEvent(event);
}

链接:QT-qtablewidget表头添加复选框QHeaderView资源-优快云文库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值