默认情况下,`QTableView`中的单元格内容是不支持自动换行的,而是将文本截断或者显示省略号。要实现内容自动换行。要用Delegate
迅雷demo
链接:https://pan.xunlei.com/s/VO8lJGf-bokGg8VVVKUwiF1AA1?pwd=xxce#
复制这段内容后打开手机迅雷App,查看更方便
#include <QStyledItemDelegate>class WrapDelegate : public QStyledItemDelegate
{Q_OBJECT
public:WrapDelegate(QObject * parent = 0);~WrapDelegate();void paint(QPainter *painter, const QStyleOptionViewItem & option,const QModelIndex & index) const override;
};
重新这里的paint
void WrapDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{auto text = index.model()->data(index, Qt::DisplayRole).toString();//注意,这里必须用TextWrapAnywhere! TextWordWrap无效painter->drawText(option.rect, Qt::TextWrapAnywhere | Qt::AlignVCenter, text);
}
使用方法
auto pTable = new QTableView;pTable->setModel(&m_model);auto pDelegate0 = new WrapDelegate();auto pDelegate1 = new WrapDelegate();auto pDelegate2 = new WrapDelegate();pTable->setItemDelegateForColumn(0, pDelegate0);pTable->setItemDelegateForColumn(1, pDelegate1);pTable->setItemDelegateForColumn(2, pDelegate2);