I have a QTreeView
and want different background colors for rows, depending on their content. To achieve this, I derived a class MyTreeView
from QTreeView
and implemented the paint method as follows:
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);
}
Initially, I set setAlternatingRowColors(true);
for the QTreeView.
My problem: Setting the color for QPalette::Base has no effect. Every second row remains white.
However, setting QPalette::AlternateBase works as expected.
I tried setAutoFillBackground(true)
and setAutoFillBackground(false)
without any effect.
Are there any hints how to solve this problem? Thank you.
Remark: Setting the color by adapting MyModel::data(const QModelIndex&, int role)
for Qt::BackgroundRole
does not provide the desired result. In this case, the background color is used only for a part of the row. But I want to color the full row, including the left side with the tree navigation stuff.
Qt Version: 4.7.3
Update:
For unknown reasons QPalette::Base
seems to be opaque.
setBrush does not change that.
I found the following workaround:
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);
}
fillRect
lead me to a reasonable workaround. – Siderite