我有一个QTreeView
并希望根据行的内容使用不同的背景颜色。为了实现这一目标,我导出了一个class MyTreeView
from QTreeView
并实现了paint方法如下:
void MyTreeView::drawRow (QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
QStyleOptionViewItem newOption(option);
if (someCondition)
{
newOption.palette.setColor( QPalette::Base, QColor(255, 0, 0) );
newOption.palette.setColor( QPalette::AlternateBase, QColor(200, 0, 0) );
}
else
{
newOption.palette.setColor( QPalette::Base, QColor(0, 0, 255) );
newOption.palette.setColor( QPalette::AlternateBase, QColor(0, 0, 200) );
}
QTreeView::drawRow(painter, newOption, index);
}
最初,我设置setAlternatingRowColors(true);
对于 QTreeView。
我的问题:设置颜色为QPalette::Base 没有效果。每隔一行保持白色。
然而,设置QPalette::AlternateBase 按预期工作。
我试过setAutoFillBackground(true)
and setAutoFillBackground(false)
没有任何影响。
有任何提示如何解决这个问题吗?谢谢。
Remark:通过适应设置颜色MyModel::data(const QModelIndex&, int role)
for Qt::BackgroundRole
没有提供所需的结果。在这种情况下,背景颜色仅用于行的一部分。但我想为整行着色,包括带有树导航内容的左侧。
Qt版本: 4.7.3
Update:由于未知原因QPalette::Base
似乎是不透明的。
setBrush 不会改变这一点。
我找到了以下解决方法:
if (someCondition)
{
painter->fillRect(option.rect, Qt::red);
newOption.palette.setBrush( QPalette::AlternateBase, Qt::green);
}
else
{
painter->fillRect(option.rect, Qt::orange);
newOption.palette.setBrush( QPalette::AlternateBase, Qt:blue);
}