问题
I followed this post which explains on how to use HTML with TableViews using Delegates.
Now here is a twist and I cant figure this out
How can I make my html word wrap. For instance if the text is :
"I am the very model of a modern major general, I've information vegetable animal and mineral, I know the kinges of England and I quote the fights historical from Marathon to Waterloo in order categorical..."
Currently everything appears on one line on the cell of the tableView. Is there a way for me to word wrap this ? I have the following paint method
void HTMLDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
{
QStyleOptionViewItemV4 options = option;
initStyleOption(&options, index);
painter->save();
QTextDocument doc;
doc.setHtml(options.text);
options.text = "";
options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);
painter->translate(options.rect.left(), options.rect.top()+0);
QRect clip(0, 0, options.rect.width(), options.rect.height());
doc.drawContents(painter, clip);
painter->restore();
}
回答1:
Be aware that performance will be terrible.
void HTMLDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
{
QStyleOptionViewItemV4 options = option;
initStyleOption(&options, index);
painter->save();
QTextDocument doc;
QTextOption textOption(doc.defaultTextOption());
textOption.setWrapMode(QTextOption::WordWrap);
doc.setDefaultTextOption(textOption);
doc.setHtml(options.text);
doc.setTextWidth(options.rect.width());
options.text = "";
options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);
painter->translate(options.rect.left(), options.rect.top()+0);
QRect clip(0, 0, options.rect.width(), options.rect.height());
doc.drawContents(painter, clip);
painter->restore();
}
来源:https://stackoverflow.com/questions/23802170/word-wrap-with-html-qtabelview-and-delegates