Search code examples
pythonqttreeqtreeview

Python: PyQt QTreeview example - selection


I'm using Python 2.7 and Qt designer and I'm new to MVC: I have a View completed within Qt to give me a directory tree list, and the controller in place to run things. My question is:

Given a Qtree view, how may I obtain a directory once a dir is selected?

enter image description here

Code snap shot is below, I suspect it's SIGNAL(..) though I'm unsure:

class Main(QtGui.QMainWindow):
  plot = pyqtSignal()

  def __init__(self):
    QtGui.QMainWindow.__init__(self)
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)

    # create model
    model = QtGui.QFileSystemModel()
    model.setRootPath( QtCore.QDir.currentPath() )

    # set the model
    self.ui.treeView.setModel(model)

    **QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)**

  def test(self):
    print "hello!"

Solution

  • The signal you're looking for is selectionChanged emmited by the selectionModel owned by your tree. This signal is emmited with the selected item as first argument and the deselected as second, both are instances of QItemSelection.

    So you might want to change the line:

    QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)
    

    to

    QtCore.QObject.connect(self.ui.treeView.selectionModel(), QtCore.SIGNAL('selectionChanged()'), self.test)
    

    Also I recommend you to use the new style for signals and slots. Redefine your test function as:

     @QtCore.pyqtSlot("QItemSelection, QItemSelection")
     def test(self, selected, deselected):
         print("hello!")
         print(selected)
         print(deselected)
    

    Here you have a working example:

    from PyQt4 import QtGui
    from PyQt4 import QtCore
    
    class Main(QtGui.QTreeView):
    
      def __init__(self):
    
        QtGui.QTreeView.__init__(self)
        model = QtGui.QFileSystemModel()
        model.setRootPath( QtCore.QDir.currentPath() )
        self.setModel(model)
        QtCore.QObject.connect(self.selectionModel(), QtCore.SIGNAL('selectionChanged(QItemSelection, QItemSelection)'), self.test)
    
      @QtCore.pyqtSlot("QItemSelection, QItemSelection")
      def test(self, selected, deselected):
          print("hello!")
          print(selected)
          print(deselected)
    
    if __name__ == '__main__':
        import sys
        app = QtGui.QApplication(sys.argv)
        w = Main()
        w.show()
        sys.exit(app.exec_())
    

    PyQt5

    In PyQt5 is a little bit different (thanks to Carel and saldenisov for comments and aswer.)

    ... connect moved from being an object method to a method acting upon the attribute when PyQt went from 4 to 5

    So instead the known:

    QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)
    

    now you write:

    class Main(QTreeView):
        def __init__(self):
            # ...  
            self.setModel(model)
            self.doubleClicked.connect(self.test)  # Note that the the signal is now a attribute of the widget.
    

    Here is a the example (by saldenisov) using PyQt5.

    from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication
    
    class Main(QTreeView):
        def __init__(self):
            QTreeView.__init__(self)
            model = QFileSystemModel()
            model.setRootPath('C:\\')
            self.setModel(model)
            self.doubleClicked.connect(self.test)
    
        def test(self, signal):
            file_path=self.model().filePath(signal)
            print(file_path)
    
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        w = Main()
        w.show()
        sys.exit(app.exec_())