问题描述
这个问题是进一步发展,并且不同,虽然可能类似于。
This question is further development of this post and is different, though may seem similar as this one.
我试图重新实现 QHeaderView :: paintSection
,以便从模型返回的背景将被遵守。我尝试这样做
I am trying to reimplement QHeaderView::paintSection
, so that the background returned from the model would be honored. I tried to do this
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
调用没有任何区别。
However, it didn't work - if I make QHeaderView::paintSection
call, nothing I draw with the painter is visible (I also tried drawing a diagonal line). If I remove QHeaderView::paintSection
call, the line and the background will be visible.Making the fillRect
call before vs. after the QHeaderView::paintSection
doesn't make any difference.
我不知道,什么是 QHeaderView :: paintSection
这使得我不可能绘制东西顶部。
是否有办法克服它,而不重新实现 QHeaderView :: paintSection
有什么?
I wonder, what is it that QHeaderView::paintSection
does that makes it impossible for me to draw something on top of it.And whether there is a way to overcome it without reimplementing everythning what QHeaderView::paintSection
does?
所有我需要做的是给某个单元格添加一定的阴影 - 我仍然希望单元格中的所有内容(文本,图标,渐变背景等)被绘成现在...
All I need to do is to add a certain shade to a certain cell - I still want everything in the cell (text, icons, gradient background etc.) to be painted as it is now...
推荐答案
很明显为什么第一个 fillRect
不工作。 paintSection
之前绘制的一切都被基本绘画覆盖。
It is obvious why the first fillRect
doesn't work. Everything that you paint before paintSection
is overridden by base painting.
第二个调用更有趣。
通常所有绘制方法都保留 painter
状态。这意味着当你调用 paint
它看起来像画家状态没有改变。
Usually all paint methods preserves painter
state. It means that when you call paint
it looks like the painter state hasn't been changed.
c $ c> QHeaderView :: paintSection 破坏画家状态。
Nevertheless QHeaderView::paintSection
spoils the painter state.
要绕过这个问题,您需要自己保存和恢复状态:
To bypass the issue you need to save and restore the state by yourself:
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>());
}
这篇关于什么是QHeaderView :: paintSection这样做,所有我做的画家之前或之后被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!