1

I am trying to use a QTableWidget (I also tried a QTableView) to tabulate some data. I expected the last column to stretch and fill the parent, but it isn't. I found a couple of answer on Stackoverflow which asked me to do the following:

QTableWidget* table = new QTableWidget();
QHeaderView* headerView = new QHeaderView(Qt::Horizontal);
table->setWindowTitle(QString::fromUtf8("QTableWidget Header Stretch"));
table->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
table->setColumnCount(2);
table->setRowCount(1);
//Set Header Label Texts Here
table->setHorizontalHeaderLabels(QString("HEADER 1;HEADER 2").split(";"));
table->setItem(0,0,new QTableWidgetItem("CELL 1"));
table->setItem(0,1,new QTableWidgetItem("CELL 2"));
headerView->sectionResizeMode(QHeaderView::Stretch);
//add the stretch here
headerView->stretchLastSection();
table->setHorizontalHeader(headerView);
table->show();

However, it is still not stretching to fill, as evident from the following picture:

enter image description here

Any idea how do I do it? I guess most of the answers concerned Qt 4, I am using Qt 5.

SexyBeast
  • 7,913
  • 28
  • 108
  • 196

1 Answers1

3

You probably want:

headerView->setStretchLastSection(true);
Sebastian Lange
  • 3,879
  • 1
  • 19
  • 38
  • Read again and find me using ``**set**StretchLastSection(true);`` – Sebastian Lange Nov 13 '14 at 10:52
  • Umm, right. Sorry, my bad. Works. On an unrelated note, even if I am adding like 30 rows, I find the table view height limited to the one shown in the picture, with the remaining rows being accessible through scrolling. How do I set it such that the table expands to fit the maximum desktop height, after which only scroll should appear? – SexyBeast Nov 13 '14 at 11:01
  • calculate the required size of your table (which has an scroll area included) and programatically resize your mainwindow up to screen size. – Sebastian Lange Nov 13 '14 at 11:29
  • Yup, doing that. Thanks. – SexyBeast Nov 13 '14 at 11:56