您要查找的信号是树所拥有的selectionModel发出的
selectionChanged 。发出此信号,其中 选择的 项目作为第一个参数, 取消选择的
作为第二个参数,两者都是QItemSelection的实例。
因此,您可能需要更改以下行:
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)至
QtCore.QObject.connect(self.ui.treeView.selectionModel(), QtCore.SIGNAL('selectionChanged()'), self.test)另外,我建议您对信号和插槽使用新样式。将
test功能重新定义为:
@QtCore.pyqtSlot("QItemSelection, QItemSelection") def test(self, selected, deselected): print("hello!") print(selected) print(deselected)这里有一个工作示例:
from PyQt4 import QtGuifrom PyQt4 import QtCoreclass 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中有一点不同(感谢Carel和saldenisov的评论和请求。)
…当PyQt从4变为5时,连接已从对象方法移到了作用于属性的方法
所以改为已知:
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL('clicked()'), self.test)现在您写:
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.
这是使用PyQt5的示例(由saldenisov撰写)。
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplicationclass 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_())


