Python:PyQt QTreeview示例-选择
我使用的是Python 2.7和Qt设计器,而我是MVC的新手:我在Qt中完成了一个View,为我提供了目录树列表,并在适当的位置运行了控制器。我的问题是:
给定Qtree视图,一旦选择了目录,如何获得目录?
下面是代码快照,我不确定是SIGNAL(..):
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!"
-
您要查找的信号是树所拥有的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 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中有一点不同(感谢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,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_())