3

这个问题是这篇文章的进一步发展并且是不同的,虽然可能看起来与这个相似。

我正在尝试重新实现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呼叫,线路和背景将可见。fillRect之前和之后拨打电话没有QHeaderView::paintSection任何区别。

我想知道,是什么QHeaderView::paintSection让我无法在它上面画一些东西。是否有办法在不重新实现所有内容的情况下克服它QHeaderView::paintSection

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

4

1 回答 1

8

很明显为什么第一个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>());             
}
于 2015-06-17T09:52:36.650 回答