QTableView根據內容自動調整大小(resizeColumnToContents解決不了的)

前言

最近使用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)

表頭將自動根據整個行或者列的內容去調整表頭單元格到最佳的大小。用戶或者程序員通過代碼都不能改變它的大小。





發佈了92 篇原創文章 · 獲贊 142 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章