【主题】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。。。。。。。。
今天就到这里了,喜欢的话就点个赞吧!