How do you set the column width on a QTreeView?

ashground picture ashground · Dec 3, 2011 · Viewed 21.1k times · Source

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?

Answer

ekhumoro picture ekhumoro · Dec 3, 2011

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_())