您的位置:首页 > 编程语言 > Qt开发

QTableView根据内容自动调整大小(resizeColumnToContents解决不了的)

2017-11-23 19:12 4876 查看

前言

最近使用QTableView比较频繁,出现了一些比较奇葩的问题,其中之一就是QTableView在显示来自模型的数据时,经常会显示...省略了内容的后半部分。
如下图:



查看帮助文档可以找到resizexxxxToContents()系列接口:
根据内容自动调整某列的列宽
void QTableView::resizeColumnToContents ( int column ) [slot]

根据内容自动调整所有列的列宽
void QTableView::resizeColumnsToContents () [slot]

根据内容自动调整某一行的行高
void QTableView::resizeRowToContents ( int row ) [slot]

根据内容自动调整所有行的行高。
void QTableView::resizeRowsToContents () [slot]

楼主之前的项目中也是通过这系列接口实现了显示不全的问题,但是这次同样调用了这些接口却还是解决不了显示不全的问题,于是楼主就开始要吐槽Qt提供的API了,这不是坑广大的Qter们吗,这系列API明显就是告诉开发者是解决表格内容显示不全的问题,但是却不是都能达到效果。

最终解决方法(通过设置表头属性解决)

折腾好久发现确实通过QTableView提供的API解决不了问题,于是就想到通过设置QTableView的表头属性能不能解决,果然最后各种折腾终于可以表格中全部内容了。
先上结果图:



源码示例:
tableView = createView(mySqlQueryModel, QObject::tr("可颂坊报表系统"));
//tableView->resizeColumnsToContents();
tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
tableView->horizontalHeader()->setMinimumSectionSize(100);
//tableView->horizontalHeader()->setSectionsMovable(true);
本着爱折腾的精神,楼主又进一步思考了一些问题:是resizexxxxToContents()系列接口和表头的setSectionResizeMode()接口的同事作用还是只有表头的setSectionResizeMode()接口就可以解决显示不全问题?最后发现1.单独调用resizexxxxToContents()系列接口解决不了;2.同时调用resizexxxxToContents()系列接口和表头的setSectionResizeMode()接口解决了显示不全问题;3.单独调用表头的setSectionResizeMode()接口就可以解决显示不全问题。最终,楼主发现起作用的是表头的setSectionResizeMode()接口!所以当使用QTableView的resizexxxxToContents()系列接口可以解决显示不全的问题的时候就单独使用这系列的接口,行不通的话就使用表头的setSectionResizeMode()接口!

附录:表头(QHeaderView)的setSectionResizeMode()接口枚举参数
enum ResizeMode
{
Interactive,
Stretch,
Fixed,
ResizeToContents,
Custom = Fixed
};

枚举常量



中文描述

英文描述

QHeaderView::Interactive

0

The user can resize the section. The section can also be resized programmatically usingresizeSection(). The section size defaults todefaultSectionSize.
(See alsocascadingSectionResizes.)

用户可以重新调整表头的大小,也可以使用resizeSection()重新调整表头的大小。

QHeaderView::Fixed

2

The user cannot resize the section. The section can only be resized programmatically usingresizeSection(). The section size defaults todefaultSectionSize.

用户不可以重新调整表头的大小,只可以使用resizeSection()重新调整表头的大小。

QHeaderView::Stretch

1

QHeaderView will automatically resize the section to fill the available space. The size cannot be changed by the user or programmatically.

表头将会调整单元格到可得的空间。用户或者程序员通过代码都不能改变它的大小。

QHeaderView::ResizeToContents

3

QHeaderView will automatically resize the section to its optimal size based on the contents of the entire column or row. The size cannot be changed by the user or programmatically. (This value
was introduced in 4.2)

表头将自动根据整个行或者列的内容去调整表头单元格到最佳的大小。用户或者程序员通过代码都不能改变它的大小。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息