Solved QTableView header resizes when clicked
-
I have a
QTableView
and I set the size of the headers usingsetColumnWidth
and I also have thesetSortingEnabled
to true however if I click in any header the size of the columns is resized.How to keep the columns width even when the headers are clicked?
-
@Mr-Gisa
If that really is the behviour you see, and if noone states how the widths can be preserved on new query (from header click), you can save the widths before the sort and restore afterward. -
Sorry my ignorance but I really didn't understand what you said :(
-
@Mr-Gisa
You have header click method which sets which column to sort by, causing the refresh?Before setting the sort column, read the current column widths via
columnWidth()
first, let it repopulate, and restore widths viasetColumnWidth()
correspondingly. -
You have header click method which sets which column to sort by, causing the refresh?
Not, it's only the
QTableView
with thesetSortingEnabled
as true, nothing more than that.ui->`tableView->setModel(mProxyModel); ui->`tableView->setMouseTracking(true); ui->`tableView->setSortingEnabled(true); ui->`tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->`tableView->setSelectionMode(QAbstractItemView::SingleSelection); ui->`tableView->horizontalHeader()->setStretchLastSection(true); ui->`tableView->verticalHeader()->hide(); ui->`tableView->setColumnWidth(0, 230); ui->`tableView->setColumnWidth(1, 270); ui->`tableView->setColumnWidth(2, 270); ui->`tableView->setColumnWidth(3, 80); ui->`tableView->setColumnWidth(4, 80); ui->`tableView->setColumnWidth(5, 80);
That is how I set the table up.
If the table is empty and I click on the header it resizes the column width, it only doesn't resize when I have items in the table.
How to prevent the header to resize if there's no item in it?
-
@Mr-Gisa
So I'm saying if, for whatever reason, even if it's a Qt bug, you want to know about a column click you can use something like https://forum.qt.io/topic/87849/how-do-i-detect-which-column-was-clicked-in-a-qtableview-header/5. And then do what I said about saving & restoring your desired column widths.If the table is empty and I click on the header it resizes the column width, it only doesn't resize when I have items in the table.
That's probably a "feature". Qt table views don't seem too interested if they have no rows to show. Just an observation.
You could even presumably use the above click-detection and not pass the signal on if your rows are empty, if that's the only case where it goes wrong and you don't care in that case about doing the sorting.
-
Thanks, I did the way you said and it's working fine.