15

Bear with me, I'm still new to QT and am having trouble wrapping my brain around how it does things.

I've created and populated a QTreeView with two columns:

class AppForm(QMainWindow):
    def __init__(self, parent = None):
        super(AppForm, self).__init__(parent)
        self.model = QStandardItemModel()
        self.view = QTreeView()
        self.view.setColumnWidth(0, 800)
        self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.view.setModel(self.model)
        self.setCentralWidget(self.view)

Everything's working great, except the columns are extremely narrow. I hoped that setColumnWidth(0, 800) would widen the first column, but it doesn't seem to be having any effect. What's the proper method for setting column widths?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
ashground
  • 239
  • 2
  • 3
  • 10

2 Answers2

24

When you call setColumnWidth, Qt will do the equivalent of:

self.view.header().resizeSection(column, width)

Then, when you call setModel, Qt will (amongst other things) do the equivalent of:

self.view.header().setModel(model)

So the column width does get set - just not on the model the tree view ends up with.

tl;dr: set the column width after you set the model.

EDIT

Here's a simple demo script based on your example:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.model = QtGui.QStandardItemModel()
        self.view = QtGui.QTreeView()
        self.view.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.view.setModel(self.model)
        self.setCentralWidget(self.view)
        parent = self.model.invisibleRootItem()
        for item in 'One Two Three Four'.split():
            parent.appendRow([
                QtGui.QStandardItem(item),
                QtGui.QStandardItem(),
                QtGui.QStandardItem(),
                ])
        self.view.setColumnWidth(0, 800)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • I moved setColumnWidth below setModel, but it still doesn't seem to be having an effect. Is the problem that I haven't populated it or set the amount of columns yet? – ashground Dec 05 '11 at 18:32
  • @ashground. I've added a demo script to my answer that works for me. – ekhumoro Dec 05 '11 at 18:40
  • Awesome -- I moved setColumnWidth into a different function so that it's called after it populates the tree. Everything's working as expected now. Thanks for your help! – ashground Dec 05 '11 at 19:57
12
self.view.resizeColumnToContents(0)

This makes sure that given column's width and height are set to match with content.

Bear
  • 550
  • 9
  • 25
galactor88
  • 121
  • 1
  • 3