QTableView中使用Delegate方式来实现对特定列的文本进行换行

admin 2022年9月15日10:50:04评论52 views字数 1108阅读3分41秒阅读模式

问题:由于表格的一个列中,有个别文本过长,默认情况下,QTableView不支持对某列的文本换行,所以需要通过Delegate方式来实现这样的效果

头文件的Delegate

#pragma once
#include #include
class WrapTextDelegate : public QStyledItemDelegate{ Q_OBJECT
public: explicit WrapTextDelegate(QObject *parent = Q_NULLPTR); ~WrapTextDelegate();
public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;};

Delegate实现文件:

#include "WrapTextDelegate.h"
WrapTextDelegate::WrapTextDelegate(QObject *parent) : QStyledItemDelegate(parent){}
WrapTextDelegate::~WrapTextDelegate(){}
void WrapTextDelegate::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); //如果当前有焦点,就绘制一个焦点矩形,否则什么都不做 // drawFocus(painter, option, option.rect);

}

最后在初始化QTableView的代码中写下:

auto delegate = new WrapTextDelegate();ui->table->setItemDelegateForColumn(column, delegate);

这样就完成了。如果你想用setTextElideMode(Qt::TextElideMode mode)来达到Wrap文本的效果,也可以,不过我觉得这么做不太美观。

QTableView中使用Delegate方式来实现对特定列的文本进行换行

原文始发于微信公众号(汇编语言):QTableView中使用Delegate方式来实现对特定列的文本进行换行

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年9月15日10:50:04
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   QTableView中使用Delegate方式来实现对特定列的文本进行换行http://cn-sec.com/archives/1296899.html

发表评论

匿名网友 填写信息