How to set Word Wrap text in QItemDelegate::drawDisplay overidden method without text being clipped
-
I have a QTableView which gets it data from QAbstractTableModel. But the model can contain html strings also. So to make the html tags work i have created a delegate and overriden the drawDisplay method. so that i can set the text as html to the document as mentioned in the below thread :
@class HtmlDelegate : public QItemDelegate { public: HtmlDelegate(QObject *parent = 0) : QItemDelegate(parent) {}
// This function is only called to paint the text
void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option,
const QRect &rect, const QString &text) const
{
QTextDocument doc;// Since the QTextDocument will do all the rendering, the color, // and the font have to be put back inside the doc QPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) cg = QPalette::Inactive; QColor textColor = option.palette.color(cg, QPalette::Text); doc.setDefaultStyleSheet(QString("body { color: %1}") .arg(textColor.name())); doc.setDefaultFont(option.font); // This is the actual code for word wrap. QTextOption txtOption; txtOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); doc.setDefaultTextOption(txtOption); doc.setTextWidth(rect.width()); doc.setHtml(text); painter->save(); painter->translate(rect.topLeft()); doc.drawContents(painter); painter->restore();
}
// bold and underlined characters take more space
// so you have to redefine this function as well
// (if you have a checkbox or an icon in the item, you will have
// to include their size to the returned value)
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QTextDocument doc;
doc.setTextWidth(QItemDelegate::sizeHint(option, index).width());
doc.setHtml(index.data(Qt::DisplayRole).toString());return doc.size().toSize();
}
};@I tried this but not working completely though have some problems with height of the row while resizing the widget. Is this the correct way of implementing drawDisplay and sizeHint to accept html and word wrap the text ?
Any help is highly appreciable !!