8

Actually the title contains all information needed. Is there an easy function like tableview.resizeColumnsToContents() that allows the maximization of all column widths within the widget size? My columns are narrow so the table looks very compact.

gruenkohl
  • 103
  • 1
  • 8

2 Answers2

14

If you want the columns to expand uniformly, you could also set the resize mode

tableview.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

In pyqt5 setResizeMode is no longer available. Instead, use setSectionResizeMode and QHeaderView in the QtWidgets module.

Demitri
  • 13,134
  • 4
  • 40
  • 41
Stephen Terry
  • 6,169
  • 1
  • 28
  • 31
  • Thanks for the answer, Can you please tell me how to do this and enable it from having a scrollbar, so when you have more columns, it will still make the width bigger? – U13-Forward Aug 21 '18 at 07:34
  • 2
    2020 update: `tableview.horizontalHeader().setSectionResizeMode(i, QtWidgets.QHeaderView.Stretch)` where `i` is the column index – Santi Peñate-Vera Jan 16 '20 at 18:20
  • @SantiPeñate-Vera the section index is optional. There are two overrides for `setSectionResizeMode`, one that [sets the mode for *all* sections](https://doc.qt.io/qt-5/qheaderview.html#setSectionResizeMode), and the other that [sets the mode for a given index](https://doc.qt.io/qt-5/qheaderview.html#setSectionResizeMode-1). – musicamante Jun 01 '22 at 17:15
5

See resizeColumnsToContents.

There's also a stretchLastSection property that can be used (see QTableView).

Macke
  • 24,812
  • 7
  • 82
  • 118
  • stretchLastSection, I missed that one. Thank you! – gruenkohl Jun 16 '11 at 14:34
  • 1
    @gruenkohl Since it sounds like @Macke answered your question, you should mark his answer as accepted by clicking on the check sign. Similarly, if the answer is good, though perhaps not the solution to your problem, you should click the up arrow to give it a vote. – Kaleb Pederson Jun 16 '11 at 14:54