Setting a fixed width in QTreeView based on contents

451 views
Skip to first unread message

kiteh

unread,
Sep 5, 2018, 3:29:39 PM9/5/18
to Python Programming for Autodesk Maya
Hello all,

I am creating a Gui where it utilizes a QTreeView to populate some items in the scene, in a similar fashion as the Outliner.
(Pardon me in advance for my PyQt as I have just started out learning)
Currently I am having an issue in setting a 'fixed' width for the QTreeView where I am trying to capture/ fit the width based on the longest length within the hierarchy.

In the following example, the width of the QTreeView will be determined by `custom_sphere_01`
|-- Group01
|--|-- ItemA
|--|--|-- custom_sphere_01
|--|-- ItemB
|--|--|-- sphere_01

I have tried a few methods in the QTreeView, eg. `resizeColumnToContents` but it does not seems to be working etc.

self._tree_widget = QtGui.QTreeView()

# QAbstractItemModel
models
= MyMode()
self._tree_widget.setModel(models)

# It does not seems to resize the contents.
# self._tree_widget.header().setResizeMode(0, QtGui.QHeaderView.ResizeToContents)

self._tree_widget.header().hide()
self._tree_widget.expandAll()
self._tree_widget.setFixedWidth(self._tree_widget.sizeHint().width())

# Giving a pre-defined value to set a fixed width does works...
# self._tree_widget.setFixedWidth(100)

Wondering if anyone has any advice or any other ways to handle it?

Michael Boon

unread,
Sep 5, 2018, 6:48:12 PM9/5/18
to Python Programming for Autodesk Maya
I've got some old code that looks like this...from memory it does what you want. This is in my QTreeView __init__:
self.header().setSectionResizeMode(QtWidgets.QHeaderView.Fixed) # This is setResizeMode in PySide1
for i, c in enumerate(self.model().columns):
   
self.header().resizeSection(i, c.pixelWidth)

Reply all
Reply to author
Forward
0 new messages