QTableView表头内容根据列宽自动换行

博客作者通过继承QHeaderView并重写paintSection方法,实现了QTableView表头的列宽自动换行功能。代码示例展示了如何在表头绘制时设置文字换行并居中显示,同时给出了设置固定高度的示例。文章鼓励读者尝试实现自适应列高的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【主题】QTableView的表头即QHeaderView根据表头的列宽自动换行。

本来常规做法就是设置wrap属性,或者实现itemdelegate,然后搜了好多资料,发现。。。

QHeaderview根本就没有wrap属性,而且也不支持itemdelegate,找了好多没找到,然后就自己尝试吧,我想着它总要绘制吧。所以干脆一点继承QHeaderView实现一个子类。在绘制的时候去实现,上代码如下

1、CustomHeaderView.h文件如下

#include <QHeaderView>
#include <QPainter>

class CustomHeaderView : public QHeaderView
{
    Q_OBJECT

public:
    CustomHeaderView(Qt::Orientation orientation = Qt::Horizontal,QWidget *parent = nullptr);    //这里为了省事,给默认值为水平表头,因为我正好使用水平的表头
    ~CustomHeaderView()

protected:
    virtual void paintSection(Qpainter *painter, const QRect &rect, int logicalIndex) const;
};

2、CustomHeaderView.cpp文件如下

#include "CustomHeaderView.h"


CustomHeaderView::CustomHeaderView(Qt::Orientation orientation ,QWidget *parent)
:QHeaderView(orientation,parent)
{
}
CustomHeaderView::~CustomHeaderView()
{
}

void CustomHeaderView::paintSection(Qpainter *painter, const QRect &rect, int logicalIndex) const
{
    //就简单几句
    //拿到text数据,在写数据的时候,设置textwordwrap,居中。
    QString textstr = model()->headerData(visualIndex(logicalIndex),Qt::Horizontal).toString();
    painter->save();
    painter->drawText(rect,Qt::TextWordWrap | Qt::AlignCenter, textstr);
    painter->restore();
}

搞定了,visualindex是防止有什么排序之类的,这样可以拿到真实数据,我这里没有排序,所以去掉了,也是一样的,亲测有效,如下,直接传logicalIndex

QString textstr = model()->headerData(logicalIndex,Qt::Horizontal).toString();

3、使用,把自定义的title设置给QTableView就可以了。

QTableView table = new QTableView;
table.setHorizontalHeader(new CustomHeaderView(Qt::Horizontal,table));

//设置两行高度
table.horizontalHeader().setFixedHeight(36);

效果:

 

4、进阶

这样有一个问题,就是列的高度不能自己变,因为我这里只要求行,高了不好看,所以我就提前设置高度2行如上代码。但实际上是可以自定义的,应该是下面的函数,大家有兴趣可以实现一下

QSize QHeaderView::sectionSizeFromContents(int logicalIndex) const

。。。。。。。。end。。。。。。。。

今天就到这里了,喜欢的话就点个赞吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值