I have a QTreeView and different lines require different background colors, depending on their contents. For this, I got the class MyTreeView from QTreeView and implemented the drawing 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); }
First I set setAlternatingRowColors(true); for QTreeView.
My problem: Color setting for QPalette :: Base has no effect . Every second line remains white.
However, setting QPalette :: AlternateBase works as expected . I tried setAutoFillBackground(true) and setAutoFillBackground(false) without any effects.
Are there any tips on how to solve this? Thanks.
Note. Setting the color by adapting MyModel::data(const QModelIndex&, int role) for Qt::BackgroundRole does not give the desired result. In this case, the background color is used only for part of the line. But I want to colorize the entire line, including the left side, using the navigation tree.
Qt Version: 4.7.3
Update: For unknown reasons, QPalette::Base seems opaque. setBrush does not change this. 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); }