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:

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?
source share