Overriding Qt Stylesheet in QStyledItemDelegate

1.2k views Asked by At

I have a QTableView that is using a custom QStyledItemDelegate to render each row of the table. A stylesheet is setting the background color of the selected row on the TableView by doing the following:

QTableView::item::selected {
    background-color: $highlight_color; //this parses to #FFFFFF
}

This works as it should, but under certain conditions I would like to adjust the alpha of the selected row's background by making it semi-transparent. I am doing this by overriding the paint() function of QStyledItemDelegate.

void CustomDelegate::paint(QPainter* painter,
                           const QStyleOptionViewItem& option,
                           const QModelIndex& index) const {
    QColor color(option.palette.color(QPalette::Highlight));

    if(isOpaque)
        color.setAlphaF(0.5);

    painter->fillRect(options.rect, QBrush(background_color));
}

This does change the color, but the color of QPalette::Highlight is not correct. Furthermore, I have tried all of the different palette color roles, and none of them reflect the background color set in the stylesheet. If I do the following, however, it works just fine (minus the opacity).

void CustomDelegate::paint(QPainter* painter,
                           const QStyleOptionViewItem& option,
                           const QModelIndex& index) const {
    QStyledItemDelegate::paint(painter, options, index);
}

I have read that combining Qt Stylesheets and QPalette is not a good idea, but my only alternative is to have another variable in the stylesheet that reflects the opacity, and I would like to avoid that at all costs.

0

There are 0 answers