class HtmlDelegate : public QStyledItemDelegate { protected: void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; }; void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 optionV4 = option; initStyleOption(&optionV4, index); QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style(); QTextDocument doc; doc.setHtml(optionV4.text); /// Painting item without text optionV4.text = QString(); style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter); QAbstractTextDocumentLayout::PaintContext ctx; // Highlighting text if item is selected if (optionV4.state & QStyle::State_Selected) ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText)); QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4); painter->save(); painter->translate(textRect.topLeft()); painter->setClipRect(textRect.translated(-textRect.topLeft())); doc.documentLayout()->draw(painter, ctx); painter->restore(); }
How to make item view render rich (html) text in Qt
最新推荐文章于 2022-02-28 22:01:57 发布
本文介绍了一个自定义的HTMLDelegate类,用于在Qt中使用QStyledItemDelegate的方式渲染HTML内容。该类通过重写paint方法实现了对QModelIndex所代表的数据进行HTML格式化的绘制,并通过调整样式选项、设置文本颜色及布局等细节确保了良好的视觉效果。
9508

被折叠的 条评论
为什么被折叠?



