The signal you are looking for is selectionChanged , labeled selectionModel , belonging to your tree. This signal is replaced with the selected element as the first argument and canceled as the second, both are instances of QItemSelection .
So you can 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)
I also recommend that you use the new style for signals and slots . Override the 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
PyQt5 is slightly different (thanks to Carel and saldenisov for comments and aswer.)
... connect went from an object method to a method that acts on an attribute when PyQt moved from 4 to 5
Therefore, instead, it is known:
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)
now you write:
class Main(QTreeView): def __init__(self):
Here is an 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_())