13

I have a QTableWidget with an N number of columns, which when the number of columns are set, they automically fill in the entire QTableWidget. When I try to dynamically change the number of columns to N/2 columns, the size of each column does not change. This results in the right half the QTableWidget being nothing but whitespace.

Conversly, if I were it reset the column count to 2*N, the column widths adjust themselves appropriately and fill the QTableWidget.

I'm wondering how I can reset the number of columns and row without the QTableWidget having any whitespace?

sj755
  • 3,944
  • 14
  • 59
  • 79

1 Answers1

32

Have you tried setting the QHeaderView's Resize Mode?

    QTableWidget* myTable = new QTableWidet;
    QHeaderView* header = myTable->horizontalHeader();
    header->setResizeMode(QHeaderView::Stretch);

Edit: As pointed out, in Qt 5:

    QTableWidget* myTable = new QTableWidet;
    QHeaderView* header = myTable->horizontalHeader();
    header->setSectionResizeMode(QHeaderView::Stretch);
Calum Murray
  • 1,102
  • 3
  • 12
  • 20
  • 4
    This works. However, `setSectionResizeMode` should be used instead. `setResizeMode` is not available in Qt5. However, it seems I have to reset the mode every time I update the row or column count. – sj755 Jul 01 '13 at 19:23
  • 1
    [QHeaderView::setStretchLastSection(true)](http://qt-project.org/doc/qt-5.0/qtwidgets/qheaderview.html#stretchLastSection-prop) might also be an option, depending on your application. – Phlucious Jul 01 '13 at 19:42
  • `myTable.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)` in pyqt5 – giuliano-oliveira Sep 22 '20 at 22:42