Ser*_*rge 3 c++ qt qpainter qheaderview
这个问题是这篇文章的进一步发展,并且有所不同,尽管可能看起来与此类似.
我正在尝试重新实现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>());
}
Run Code Online (Sandbox Code Playgroud)
然而,它没有用 - 如果我QHeaderView::paintSection打电话,我画画的任何东西都是可见的(我也尝试画一条对角线).如果我删除了QHeaderView::paintSection呼叫,则可以看到线路和背景.在fillRect之前和之后进行通话QHeaderView::paintSection没有任何区别.
我想知道,是什么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>());
}
Run Code Online (Sandbox Code Playgroud)