7

Is there any way to set column width for QTreeWidget from code? I want to chage default width of first column. I'm using PySide.

xander27
  • 3,014
  • 8
  • 30
  • 42

3 Answers3

8

QHeaderView::resizeSection() should do the trick, in C++ it would look like this:

myTreeWidget->headerView()->resizeSection(0 /*column index*/, 100 /*width*/);
Chris
  • 17,119
  • 5
  • 57
  • 60
  • I think I can adopt it for PySide. Thanks – xander27 Feb 05 '13 at 04:37
  • 2
    There is no function `headerView` in `QTreeWidget`. I think you really meant to use `QTreeWidget::header()` (at least for Qt5 - maybe the answer was for Qt4) – Raven Feb 28 '21 at 14:32
3

For people looking for a C++ Qt solution (tested with 5.12):

// Important to call setMinimumSectionSize because resizeSection wont work if your width is less than the minimum
treeWidget->header()->setMinimumSectionSize(25);
treeWidget->header()->resizeSection(1 /*column index*/, 25 /*width*/);

// You might also need to use this if you want to limit the size of your last column:
treeWidget->header()->setStretchLastSection(false);
RandomName
  • 163
  • 1
  • 10
2

In Pyside2 there is no resizeSection

you can use this in PySide2:

header = self.treeWidget.header()
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
header.setStretchLastSection(False)
header.setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch)
Rajiv Sharma
  • 6,746
  • 1
  • 52
  • 54