1

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Haus
  • 1,492
  • 7
  • 23
  • Why do not you set the highlighted color directly on the delegate and no longer use QSS? – eyllanesc Nov 03 '18 at 05:27
  • the project has custom theme support, so loading from QSS is pretty much mandatory – Haus Nov 03 '18 at 20:53
  • 1
    Well, I have to tell you that you can not access the highlight color, the painting has in this case the following phases: a QStyleOptionViewItem is created that receives some parameters to be painted that are passed to a QStyle to be painted, in that QStyle it uses a private api that accesses the QSS elements, and in that instance the highlighting is done, that is, the highlight is not done in the delegate directly but the QStyle is used, and the QStyle does not have the idea of QModelIndex. – eyllanesc Nov 03 '18 at 20:57
  • @eyllanesc Thank you, that definitely clarifies what is happening. For future knowledge: does the same order of operation apply to custom widgets that override `paint()` or `paintEvent()` as well? – Haus Nov 05 '18 at 18:36
  • 1
    in QPaintEvent iterates over the items and calls the delegate's paint method: `paintEvent(args){ for(ix it in items) {delegate.paint(ix, another_args)} }` – eyllanesc Nov 05 '18 at 18:38

0 Answers0