猿问

如何使项目视图在Qt中呈现富文本(html)

假设我的模型中包含以下项目的Qt :: DisplayRole字符串


<span>blah-blah <b>some text</b> other blah</span>

我想要QTreeView(实际上是任何项目视图)将其呈现为富文本格式。而是,项目视图默认情况下将其呈现为纯文本。如何实现所需的渲染?


实际上,这是一个搜索结果模型。用户输入文本,针对该文本搜索某些文档,然后向用户显示搜索结果,其中要搜索的单词应比周围的文本大胆。


一只斗牛犬
浏览 1551回答 3
3回答

忽然笑

我的答案主要是受@serge_gubenko的启发。但是,做了一些改进,使代码最终在我的应用程序中有用。class HtmlDelegate : public QStyledItemDelegate{protected:&nbsp; &nbsp; void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const;&nbsp; &nbsp; QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const;};void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const{&nbsp; &nbsp; QStyleOptionViewItemV4 optionV4 = option;&nbsp; &nbsp; initStyleOption(&optionV4, index);&nbsp; &nbsp; QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();&nbsp; &nbsp; QTextDocument doc;&nbsp; &nbsp; doc.setHtml(optionV4.text);&nbsp; &nbsp; /// Painting item without text&nbsp; &nbsp; optionV4.text = QString();&nbsp; &nbsp; style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter);&nbsp; &nbsp; QAbstractTextDocumentLayout::PaintContext ctx;&nbsp; &nbsp; // Highlighting text if item is selected&nbsp; &nbsp; if (optionV4.state & QStyle::State_Selected)&nbsp; &nbsp; &nbsp; &nbsp; ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText));&nbsp; &nbsp; QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);&nbsp; &nbsp; painter->save();&nbsp; &nbsp; painter->translate(textRect.topLeft());&nbsp; &nbsp; painter->setClipRect(textRect.translated(-textRect.topLeft()));&nbsp; &nbsp; doc.documentLayout()->draw(painter, ctx);&nbsp; &nbsp; painter->restore();}QSize HtmlDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const{&nbsp; &nbsp; QStyleOptionViewItemV4 optionV4 = option;&nbsp; &nbsp; initStyleOption(&optionV4, index);&nbsp; &nbsp; QTextDocument doc;&nbsp; &nbsp; doc.setHtml(optionV4.text);&nbsp; &nbsp; doc.setTextWidth(optionV4.rect.width());&nbsp; &nbsp; return QSize(doc.idealWidth(), doc.size().height());}
随时随地看视频慕课网APP
我要回答