2

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();
}
Stanislav Pankevich
  • 11,044
  • 8
  • 69
  • 129
MistyD
  • 16,373
  • 40
  • 138
  • 240

1 Answers1

4

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();
}
Marek R
  • 32,568
  • 6
  • 55
  • 140