您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python:PyQt QTreeview示例-选择

Python:PyQt QTreeview示例-选择

您要查找的信号是树所拥有的selectionModel发出的 。发出此信号,其中 项目作为第一个参数, 作为第二个参数,两者都是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中有一点不同(感谢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_())
python 2022/1/1 18:38:35 有242人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶