class WordWrapDelegate : public QStyledItemDelegate {
public:
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override {
// 获取数据
QString text = index.data(Qt::DisplayRole).toString();
// 计算文本所需空间
QTextDocument document;
document.setDefaultFont(option.font);
document.setPlainText(text);
int width = option.rect.width();
int doc_width = document.idealWidth();
if (doc_width > width) {
return QSize(width, document.size().height());
} else {
return QSize(doc_width, document.size().height());
}
}
};
评论