QTreeView使用总结3,表头、行列相关的设置方法

1,简介

上一篇文章介绍了QTreeView常用的设置API,一般情况足够使用了。

以后逐步介绍更多的其他设置方法,本篇对表头、行、列相关内容做一个综合。

 

2,表头、列

QTreeView* t;

隐藏表头:

t->header()->hide();

设置默认列宽:

t->header()->setDefaultSectionSize(100);

设置表头默认文字对齐:

t->header()->setDefaultAlignment(Qt::AlignCenter);

一般设置最后一列自适应宽度,让表头初始显示时占满行,效果比较好:

t->header()->setStretchLastSection(true);

点击QTreeView时,如果出现该列头文字加粗的情况,可以用下面接口去掉该属性:

t->header()->setHighlightSections(true);

当然,项目里的做法一般更细节,可能是对每列分别设置列宽、拉伸属性:

t->header()->resizeSection(0,100);                            //第1列宽100
t->header()->setSectionResizeMode(3,QHeaderView::Fixed);      //第4列定宽

也可以直接使用QTreeView的接口设置列宽:

void setColumnWidth(int column, int width);

设置QTreeView内容按某列排序:

t->header()->setSortIndicator(0,Qt::AscendingOrder);    //按第1列升序排序

对这些需指定某列进行设置的接口,需要QTreeView绑定model之后调用才行。因为要对数据内容进行调整。

 

3,行

设置行高:

QTreeView没有直接提供设置行高的方法,一般的方法是使用Delegate。

QItemDelegate继承,使用QTreeView::setItemDelegate设置。派生类里对sizeHint处理:

QSize MyDelegate::sizeHint ( const QStyleOptionViewItem & option,  const QModelIndex & index ) const  
{  
    QSize size = QItemDelegate::sizeHint(option, index);  
    size.setHeight( size.height() + 4 );  
    return size;  
}  

我觉得最简单的方法就是直接用qss样式表:

QTreeView::item {
	height: 30px;
}
稍后详细介绍QTreeView的样式表使用。







猜你喜欢

转载自blog.csdn.net/dpsying/article/details/79846733