Giuseppe
Giuseppe

Reputation: 153

Selecting a child as current item in a tree

Consider the following fully expanded toy tree where I make Alpha the current root:

from PyQt5 import QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setMinimumHeight(300)
        self.setMinimumWidth(100)

        my_tree = QtWidgets.QTreeWidget(self)
        my_tree.resize(100, 300)

        alpha = QtWidgets.QTreeWidgetItem(my_tree, ['Alpha'])
        beta = QtWidgets.QTreeWidgetItem(my_tree, ['Beta'])

        alpha.addChild(QtWidgets.QTreeWidgetItem(['one']))
        alpha.addChild(QtWidgets.QTreeWidgetItem(['two']))

        beta.addChild(QtWidgets.QTreeWidgetItem(['first']))
        beta.addChild(QtWidgets.QTreeWidgetItem(['second']))

        my_tree.expandAll()
        my_tree.setCurrentItem(my_tree.topLevelItem(0))

        self.show()

app = QtWidgets.QApplication([])
window = MainWindow()
app.exec_()

How can I make the first child of Alpha (i.e. one) the current and selected item, while at the same time also only expanding Beta instead of both roots?

Upvotes: 1

Views: 240

Answers (1)

Thaer A
Thaer A

Reputation: 2323

You can use setExpanded() to expand or collapse item:

alpha.setExpanded(False)

I just noticed you have my_tree.expandAll() in your code. If you'd like to collapse one of the items, use item.setExpanded(False) AFTER the .expandAll()

To set the first child in alpha as selected use:

alpha.child(0).setSelected(True)
print(alpha.child(0).isSelected()) #verify it's selected

Where to place them in your code:

.
.
        beta.addChild(QtWidgets.QTreeWidgetItem(['first']))
        beta.addChild(QtWidgets.QTreeWidgetItem(['second']))

        my_tree.expandAll()
        my_tree.setCurrentItem(my_tree.topLevelItem(0))

        alpha.setExpanded(False)
        alpha.child(0).setSelected(True)
        print(alpha.child(0).isSelected())  # verify it's selected

        self.show()

To run a function when the selection changes try the code below, it will print out the text of the item or child selected (place it before self.show):

my_tree.itemSelectionChanged.connect(lambda: selected_item())

def selected_item():
    getSelected = my_tree.selectedItems()
    if getSelected:
        baseNode = getSelected[0]
        getChildNode = baseNode.text(0)
        print(getChildNode)

Upvotes: 1

Related Questions