【主题】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 *

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

被折叠的 条评论
为什么被折叠?



