问题描述
假设我的模型具有以下字符串用于 Qt::DisplayRole 的项目
Suppose my model has items with the following string for Qt::DisplayRole
<span>blah-blah <b>some text</b> other blah</span>
我希望 QTreeView(实际上,任何项目视图)能够像富文本一样呈现它.相反,默认情况下,项目视图将其呈现为纯文本.如何实现想要的渲染?
I want QTreeView (actually, any item view) to render it like a rich text. Instead, item views render it like a pure text by default. How to achieve the desired rendering?
实际上,这是一个搜索结果模型.用户输入文本,针对该文本搜索某个文档,然后向用户显示搜索结果,搜索结果应比周围文本更粗.
Actually, this is a search results model. User enters a text, some document is searched against that text and the user is presented with search results, where the words being searched should be bolder than surrounding text.
推荐答案
我的回答主要受到@serge_gubenko 的启发.但是,为了使代码最终在我的应用程序中有用,我们做了一些改进.
My answer is mostly inspired by @serge_gubenko's one. However, there were made several improvements so that the code is finally useful in my application.
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();
}
QSize HtmlDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItemV4 optionV4 = option;
initStyleOption(&optionV4, index);
QTextDocument doc;
doc.setHtml(optionV4.text);
doc.setTextWidth(optionV4.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}
这篇关于如何使项目视图在 Qt 中呈现丰富的 (html) 文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!