QT QTableView表格左上角样式

在设置完QTableView的表头样式后,发现表格左上角是一片空白,如下图:
QT QTableView表格左上角样式_第1张图片

我们希望左上角的区域也是和表头的颜色一致,可以设置此处样式:

/*QTableView 左上角样式*/
QTableView QTableCornerButton::section {
    color: white;/*文字颜色*/
    background-color: rgb(41, 139, 201);/*背景色*/
    border: 5px solid #418bc9;/*边框*/
    border-radius:0px;/*边框圆角*/
    border-color: rgb(41, 139, 201);/*边框颜色*/
    font: bold 11pt;/*字体大小*/
    padding:12px 0 0 10px;/*内边距*/
 }

效果:
QT QTableView表格左上角样式_第2张图片

我们还想在左上角位置添加文字为“序号”,效果图如下:
QT QTableView表格左上角样式_第3张图片

实现代码:

    QAbstractButton*btn = tableView->findChild();
    if (btn)
    {
        btn->setText(QStringLiteral("序号"));
        btn->installEventFilter(this);/*注册事件 CPersonMng::eventFilter*/
        QStyleOptionHeader opt;
        opt.text = btn->text();
        QSize s = (btn->style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), btn).expandedTo(QApplication::globalStrut()));
        if (s.isValid())
            tableView->verticalHeader()->setMinimumWidth(s.width());
    }
bool CPersonMng::eventFilter(QObject* o, QEvent* e)
{
    if (e->type() == QEvent::Paint)
    {
        QAbstractButton* btn = qobject_cast<QAbstractButton*>(o);
        if (btn)
        {
            // paint by hand (borrowed from QTableCornerButton)  

            QStyleOptionHeader opt;
            opt.init(btn);
            QStyle::State state = QStyle::State_None;
            if (btn->isEnabled())
                state |= QStyle::State_Enabled;
            if (btn->isActiveWindow())
                state |= QStyle::State_Active;
            if (btn->isDown())
                state |= QStyle::State_Sunken;
            opt.state = state;
            opt.rect = btn->rect();
            opt.text = btn->text(); // this line is the only difference to QTableCornerButton  

            opt.position = QStyleOptionHeader::OnlyOneSection;
            QStylePainter painter(btn);
            painter.drawControl(QStyle::CE_Header, opt);
            return true; // eat event  

        }
    }
    return false;
}

你可能感兴趣的:(Qt)