Search code examples
pythonpysideqtreeview

Which node from TreeView is selected (PySide)?


I have a program with QTreeView and I want to disable/enable some actions in Toolbar depending on which node is selected but I don't know how to get selected node. Can anyone help?


Solution

  • In the following example I show how to know which items are selected in a QTreeView, for this we use the selectionChanged signal that returns the selected and deselected items, then iterates and obtains the QModelIndex, and through this and the model we obtain the data.

    from PySide.QtGui import *
    from PySide.QtCore import *
    
    class Main(QTreeView):
        def __init__(self):
            QTreeView.__init__(self)
            model = QFileSystemModel()
            model.setRootPath(QDir.homePath())
            self.setModel(model)
            m = self.selectionModel()
            m.selectionChanged.connect(self.onSelectionChanged)
    
        def onSelectionChanged(self, selected, deselected):
            for index in selected.indexes():
                print(self.model().data(index))
    
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        w = Main()
        w.show()
        sys.exit(app.exec_())