QT之给QTableView表头左上角添加多选/单选/全选按钮

xingyun86 2月前 93

QT之给QTableView表头左上角添加多选/单选/全选按钮

class CheckBoxHeaderView8 : public QHeaderView
{
    Q_OBJECT
private:
    int     m_checkColIndex;    //列下标
    QPoint  m_topLeft;          //勾选框起始坐标
    QSize   m_checkSize;        //勾选框大小
    int    m_nChecked;          //勾选框状态 0-未选,1-部分选择,2-全选
public:
    CheckBoxHeaderView8( int checkColumnIndex, QPoint topLeft, QSize size, Qt::Orientation orientation, QWidget * parent = 0) : QHeaderView(orientation, parent)
    {
        m_checkColIndex = checkColumnIndex;
        m_topLeft = topLeft;
        m_checkSize = size;
        m_nChecked = 0;
    }
    void setCheckState(int state)
    {
        m_nChecked = state;
    }
protected:
    void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
    {
        painter->save();
        QHeaderView::paintSection(painter, rect, logicalIndex);
        painter->restore();
        if (logicalIndex == m_checkColIndex)
        {
            QStyleOptionButton option;
            int width = 10;
            for (int i=0; i<logicalIndex; ++i)
            {
                width += sectionSize( i );
            }
            option.rect = QRect(m_topLeft.x(), m_topLeft.y(), m_checkSize.width(), m_checkSize.height());
            if(m_nChecked == 1)
            {
                painter->fillRect(option.rect, QColor(196,196,196));
            }
            else
            {
                switch (m_nChecked) {
                case 2:option.state = QStyle::State_On;break;
                default:option.state = QStyle::State_Off;break;
                }
                QCheckBox *check = new QCheckBox;
                QString sheet = QString("QCheckBox::indicator {width: %1px;  height: %2px;}").arg(m_checkSize.width()).arg(m_checkSize.height());
                check->setStyleSheet(sheet);
                this->style()->drawControl(QStyle::CE_CheckBox, &option, painter, check);
            }
        }
    }
    void mousePressEvent(QMouseEvent *event)
    {
        if (visualIndexAt(event->pos().x()) == m_checkColIndex)
        {
            m_nChecked = (m_nChecked+1)%3;
            this->updateSection(m_checkColIndex);
            emit checkStatusChange(m_nChecked);
        }
        QHeaderView::mousePressEvent(event);
    }
signals:
    void checkStatusChange(int);
};

调用方式:

{
        m_checkHeaderView = new CheckBoxHeaderView8(0, QPoint(5, 5),QSize(15, 15), Qt::Horizontal, this);
        m_checkHeaderView->setObjectName(QStringLiteral("m_checkHeaderView"));
        m_checkHeaderView->setMinimumSize(QSize(100, 100));
        ui->tableView->setHorizontalHeader(m_checkHeaderView);
        connect(m_checkHeaderView, &CheckBoxHeaderView8::checkStatusChange, this, &MyMainWindow::_SlotCheckStatusChange);
}


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回