I have a simple item delegate of QStyledItemDelegate type and inside its paint method I have this code. It renders fine, but the main thing here is that I would like the text to be selectable for copy, and this doesn’t work.
void ItemDelegate::paintBody( QPainter* painter,
const QStyleOptionViewItem& option,
const QModelIndex& index ) const
{
painter->save();
QLabel *l = new QLabel();
l->setTextFormat(Qt::RichText);
l->setTextInteractionFlags(Qt::TextSelectableByMouse);
l->setGeometry(option.rect);
l->setText("This is test");
l->setStyleSheet("QLabel { background-color : transparent; }");
l->render(painter, option.rect.topLeft());
painter->restore();
}
Because all all you’re doing is painting a QLabel. The QLabel does not ‘exist’ inside the model view you are calling for, it is only rendered in the state that you created it.
You should use
to draw the label. Do not create a new
QLabeleverytime you need to paint it, not only is this inefficient, you have also created the mother of all memory leaks by not deleting it…More importantly though, selecting text should really be a part of the editor delegate, so you should be overriding
to return a widget that can display editable rich text.