PDA

View Full Version : Adding HTML code into QTableWidget cells



a5633Oy
18th December 2013, 14:18
Hi,
I have a QTableWidget of 4 columns and many rows.
The contents of cells is loaded form a XML file that contains HTML code.
To do so, i wrote a delegate class :

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
{
QStyleOptionViewItem optionV4 = option;
initStyleOption(&optionV4, index);

QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style();

QTextDocument doc;
doc.setHtml(optionV4.text);

QAbstractTextDocumentLayout::PaintContext ctx;

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
{
QStyleOptionViewItem optionV4 = option;
initStyleOption(&optionV4, index);

QTextDocument doc;
doc.setHtml(optionV4.text);
doc.setTextWidth(optionV4.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}

It works well, but the last column which is normaly stretched when i use text plain without the delegate fonction

qtbl->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
lose the stretched parameter and the cell's height doesn't fit the multiline content.

Thanks for you help.