PDA

View Full Version : Resizing of QTableWidget and QMainWindow according to the table content



dexli
24th July 2013, 15:49
Hi all,

I searched a lot but did not find a satisfying solution.

Simple Situation

using the designer to place QTableWidget (clist) inside a MainWindow. Adding a horizontal Layout to MainWindow.

And using

ui->clist->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);

to resizing the coloums to fit the maximal content length. This works like expected

Problem:

The width of the table itself depends on the width of the MainWindow. If the MainWindow is to small the Table shows only some of the columns and one has to use the scroll bar. If the MainWindow is to wide the tablewidth is also to wide.

So how to force the MainWindow to resize to the width of the table showing all columns ?

I tried to get the width of the table, but it depends on the width of the MainWindow and not on the sum of the column width.
so i tried:



QTableWidget *t = ui->clist;
t->setVisible(false);
t->resizeColumnsToContents();
int sum = 0;
for(int i = 0; i < 10; i++ )
{
sum += t->columnWidth(i);
}
QRect g = t->geometry();
g.setWidth(sum);
t->setGeometry(g);
t->setVisible(true);
g= this->geometry();
g.setWidth(sum+100);
this->setGeometry(g);


This works more or less. But sum is only the “inner size” of the table so one has to add some additional space. (which did not fit really)

I’m sure that there is a much more simple solution to adjust the width of the MainWindow so that all columns of the table are visible but not more. Also if the content width of the table changes (because of adding/changing content) the MainWindow should also change.

So dear Gurus what did I miss ?? What is the solution ??

Thanks and have a good time
dexli

ChrisW67
25th July 2013, 00:34
So how to force the MainWindow to resize to the width of the table showing all columns ?
You don't, at least not in programs that behave in the way most people expect.

If you really must do it then you probably need to start with QHeaderView::length() and force the minimum width of the QTableView. Don't forget to handle the case of the able content being wider than the screen.