Proper highlighting with qt custom delegates

I am creating a table control that displays some additional textual data other than the ones specified in the DisplayRole of its model. In all other aspects, the display of the text and the cell must be identical. I am having trouble displaying the selected cell correctly.

I am currently using the following code:

void MatchDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (option.state & QStyle::State_Selected) painter->fillRect(option.rect, option.palette.highlight()); painter->save(); QString str = qvariant_cast<QString>(index.data())+ "\n"; str += QString::number(qvariant_cast<float>(index.data(Qt::UserRole))); if (option.state & QStyle::State_Selected) painter->setBrush(option.palette.highlightedText()); else painter->setBrush(qvariant_cast<QBrush>(index.data(Qt::ForegroundRole))); painter->drawText(option.rect, qvariant_cast<int>(index.data(Qt::TextAlignmentRole)), str); painter->restore(); } 

However, the result is as follows:

highlighted cell

The color of the text is incorrect, there is no dashing line around the cell, and when the control loses focus, the cell remains blue and does not turn light gray, as the cells do by default.

How to change the picture code to fix these problems?

+4
source share
1 answer

Please try the code below, it will work.

Set drawControl with care to draw a dashed line (let Qt take care of this internally).

Fixed (dashed line, text color and multi-line) when selecting a cell.

enter image description here

 void MatchDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 opt = option; initStyleOption(&opt, index); const QWidget *widget = option.widget; QString str = qvariant_cast<QString>(index.data())+ "\n"; str += QString::number(qvariant_cast<float>(index.data(Qt::UserRole))); opt.text = ""; //option QStyle *style = widget ? widget->style() : QApplication::style(); if (option.state & QStyle::State_Selected) { // Whitee pen while selection painter->setPen(Qt::white); painter->setBrush(option.palette.highlightedText()); // This call will take care to draw, dashed line while selecting style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget); } else { painter->setPen(QPen(option.palette.foreground(), 0)); painter->setBrush(qvariant_cast<QBrush>(index.data(Qt::ForegroundRole))); } painter->drawText(option.rect, qvariant_cast<int>(index.data(Qt::TextAlignmentRole)), str); } 
+4
source

Source: https://habr.com/ru/post/1500095/


All Articles