Word Wrap with HTML? QTabelView and Delegates

2019-07-16 09:56发布

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条回答
对你真心纯属浪费
2楼-- · 2019-07-16 10:28

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();
}
查看更多
登录 后发表回答