Qt tableview表格中换行
网上搜了好多种,,,基本确定使用代理来做,但是坑的是,有个地方很多老哥都写错了,导致折腾了我半小时,特地记录,希望帮助以后相同问题的老哥。
#include "wordwrapdelegate.h" WordWrapDelegate::WordWrapDelegate(QObject *parent) : QStyledItemDelegate(parent) { } WordWrapDelegate::~WordWrapDelegate() { } void WordWrapDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { (void)(index); QString text = index.model()->data(index, Qt::DisplayRole).toString(); //绘制文本 // painter->drawText(option.rect, Qt::TextWordWrap | Qt::AlignVCenter | Qt::AlignLeft, text); //这地方一定要用TextWrapAnywhere ,否则无效!!! painter->drawText(option.rect, Qt::TextWrapAnywhere | Qt::AlignVCenter, text); }
头文件:
#ifndef WORDWRAPDELEGATE_H #define WORDWRAPDELEGATE_H #include <QStyledItemDelegate> #include <QPainter> class WordWrapDelegate:public QStyledItemDelegate { Q_OBJECT public: // WordWrapDelegate(); // QSize SizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) override; explicit WordWrapDelegate(QObject *parent = Q_NULLPTR); ~WordWrapDelegate(); public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; #endif // WORDWRAPDELEGATE_H
引用:
//这个地方记得设置高度或者最小高度,否则即使换行,会出现显示不全的问题,宽度自行调整
for(int i=0;i<stm->rowCount();i++)
{
tableWidget->setRowHeight(i,80);
}
//这个1,2是column的列索引,记得从0开始
tableWidget->setItemDelegateForColumn(1, new WordWrapDelegate);
tableWidget->setItemDelegateForColumn(2, new WordWrapDelegate);