3

The code below create a simple QTreeWidget with two items one parented to another. I want the items to be expanded from the begining (so the user doesn't have to click arrow to expand the items):

Here is how it looks by default:

enter image description here

And here is how I would like it to be (expanded: item "C" is visible):

enter image description here

What attribute needs to be set in order for this to work?

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__() 
        parentItem=QtGui.QTreeWidgetItem('P')
        self.addTopLevelItem(parentItem)
        childItem=QtGui.QTreeWidgetItem('C')
        parentItem.insertChild(0, childItem)
        self.show()
tree=Tree()
sys.exit(app.exec_())

1 Answer 1

8

You can use QTreeWidget.expandToDepth().

In your case:

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__() 
        parentItem=QtGui.QTreeWidgetItem('P')
        self.addTopLevelItem(parentItem)
        childItem=QtGui.QTreeWidgetItem('C')
        parentItem.insertChild(0, childItem)
        self.expandToDepth(0)
        self.show()
tree=Tree()
sys.exit(app.exec_())

You could also use expandAll() to expand everything instead of only to certain depth.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.