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:
};
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;
};
To copy to clipboard, switch view to plain text mode
{
initStyleOption(&optionV4, index);
doc.setHtml(optionV4.text);
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();
}
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();
}
To copy to clipboard, switch view to plain text mode
{
initStyleOption(&optionV4, index);
doc.setHtml(optionV4.text);
doc.setTextWidth(optionV4.rect.width());
return QSize(doc.
idealWidth(), doc.
size().
height());
}
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());
}
To copy to clipboard, switch view to plain text mode
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);
qtbl->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
To copy to clipboard, switch view to plain text mode
lose the stretched parameter and the cell's height doesn't fit the multiline content.
Thanks for you help.
Bookmarks