Important: Please read the Qt Code of Conduct -

Show HTML content in QTableView column while keeping BackgroundColorRole works

  • I've created a QStyledItemDelegate subclass in order to show HTML content in a column of QTableView. I had also set backgroundColors of QTableView' rows dynamically by setting data of the model this way:

    _model->setData(index, color, Qt::BackgroundColorRole);

    If I set delegate for the column, then, It will lost backgroundColor since it will be ignored by the delegate paint() method. So, How can I modify or implement the paint() method of the delegate class in order to keep both html content enabled and keep backGroundColorRole data?

    Here is my paint() method of the delegate:

    void THTMLDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
     QStyleOptionViewItem optionV4 = option;
     initStyleOption(&optionV4, index);
     QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();
     QTextDocument doc;
     QAbstractTextDocumentLayout::PaintContext ctx;
     QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
     doc.documentLayout()->draw(painter, ctx);

  • Moderators

    Either you paint it yourself since you already have the QModelIndex at hand:

    QColor color = Qt::BackgroundColorRole ).toColor();

    or by letting the style paint the stuff. Note that this also paints the selected background.

    style->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter, widget );