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

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

【主题】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 *
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值