QHeaderView::paintSection 做了什么使得我之前或之后对画家所做的一切都被忽略了

What does QHeaderView::paintSection do such that all I do to the painter before or after is ignored

这个问题是this post and is different, though may seem similar as this one的进一步发展。

我正在尝试重新实现 QHeaderView::paintSection,以便从模型返回的背景得到尊重。我试过这样做

void Header::paintSection(QPainter * painter, const QRect & rect, int logicalIndex) const
{
    QVariant bg = model()->headerData(logicalIndex, Qt::Horizontal, Qt::BackgroundRole);
    // try before
    if(bg.isValid())                // workaround for Qt bug https://bugreports.qt.io/browse/QTBUG-46216
        painter->fillRect(rect, bg.value<QBrush>());             
    QHeaderView::paintSection(painter, rect, logicalIndex);
    // try after
    if(bg.isValid())                // workaround for Qt bug https://bugreports.qt.io/browse/QTBUG-46216
        painter->fillRect(rect, bg.value<QBrush>());             
}

但是,它没有用 - 如果我调用 QHeaderView::paintSection,我用画家画的任何东西都不可见(我也试过画对角线)。如果我删除 QHeaderView::paintSection 调用,该行和背景将可见。 在 QHeaderView::paintSection 之前和之后进行 fillRect 调用没有任何区别。

我想知道,QHeaderView::paintSection 是什么让我无法在上面画东西。 是否有一种方法可以在不重新实现 QHeaderView::paintSection 所做的一切的情况下克服它?

我需要做的就是为某个单元格添加某种阴影 - 我仍然希望单元格中的所有内容(文本、图标、渐变背景等)都按现在的样子绘制...

为什么第一个 fillRect 不起作用是显而易见的。您在 paintSection 之前绘制的所有内容都将被基础绘制覆盖。

第二个电话更有趣。

通常所有绘制方法都会保留 painter 状态。这意味着当您调用 paint 时,看起来画家状态没有改变。

不过QHeaderView::paintSection破坏了画家的状态

要绕过这个问题你需要自己保存和恢复状态:

void Header::paintSection(QPainter * painter, const QRect & rect, int logicalIndex) const
{
    QVariant bg = model()->headerData(logicalIndex, Qt::Horizontal, Qt::BackgroundRole);
    painter->save();
    QHeaderView::paintSection(painter, rect, logicalIndex);
    painter->restore();
    if(bg.isValid())               
        painter->fillRect(rect, bg.value<QBrush>());             
}