PDA

View Full Version : Selection color for progressbar in treeview



Jennie Bystrom
11th February 2011, 09:27
I have a treeview where some items contain a progressbar. This I fixed by subclassing QStyledItemDelegate and re-implementing the paint method. This works well and looks good.

I do have a problem and that is that when I select a row in the tree, the cell containing the progress-bar doesn't change its background color to the selection color. The background color stays the same as the non-selected rows which makes it look very weird.

This is my paint-method in the delegate:




void ResourceTreeDelegate::paint(QPainter *painter,
const QStyleOptionViewItem& option,
const QModelIndex& index) const
{
int column = index.column();
if (column == ResourceTreeModel::Progress) {

painter->save();

if (index.data().isNull()) {
QStyledItemDelegate::paint(painter, option, index);
}
else {
QColor backgroundColor = qvariant_cast<QColor>(index.data(Qt::BackgroundColorRole));
QColor highlightColor = option.palette.color(QPalette::Highlight);

int value = index.data().toInt();
if (value < 0) value = 0;
int x = option.rect.x();
int y = option.rect.y();
int width = option.rect.width();
int height = option.rect.height();

// make with margins
int margin = ResourceTreeDelegateConstants::PROGRESS_BAR_MARGIN ;
int progressBarHeight = ResourceTreeDelegateConstants::PROGRESS_BAR_HEIGHT ;
QRect newRect(x + margin,
y + (int)(height / 2.0) - 7,
width - (2 * margin),
progressBarHeight);

QStyleOptionProgressBar progressBarOption;
progressBarOption.palette.setColor(QPalette::Windo w, backgroundColor);
progressBarOption.palette.setColor(QPalette::Highl ight, highlightColor);
progressBarOption.rect = newRect;
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.progress = value;
progressBarOption.text = QString(" %1%").arg(QString::number(value)).leftJustified(7, ' ');
progressBarOption.textVisible = true;

painter->fillRect(option.rect, progressBarOption.palette.background());
QApplication::style()->drawControl(QStyle::CE_ProgressBar,
&progressBarOption, painter);
}

if (index.isValid()) {
painter->setPen(Qt::lightGray);
painter->drawRect(option.rect);
}

painter->restore();
}

QStyledItemDelegate::paint(painter, option, index);
}


How can I tell the progressbar to change its background when rows are selected in the tree?

norobro
11th February 2011, 18:32
You need to check for the selected state. Something like this should work:
if(option.state & QStyle::State_Selected){
// set selected colors - QPalette::Highlight & QPalette::HighlightedText
}
else {
// set unselected colors if necessary - QPalette::Window & QPalette::Text
}