gpt4 book ai didi

Python:PyQt QTreeview 示例 - 选择

转载 作者:太空狗 更新时间:2023-10-29 19:35:55 24 4
gpt4 key购买 nike

我使用的是 Python 2.7 和 Qt 设计器,我是 MVC 的新手:我有一个在 Qt 中完成的 View ,可以给我一个目录树列表,以及用于运行事物的 Controller 。我的问题是:

给定 Qtree View ,我如何在选择目录后获取目录?

enter image description here

代码快照如下,我怀疑它是 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!"

最佳答案

您要查找的信号是selectionChanged由您的树拥有的 selectionModel 发出。此信号以 selected 项目作为第一个参数发出,取消选择 作为第二个参数,两者都是 QItemSelection 的实例。 .

所以你可能想要更改行:

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

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

我还建议您使用 new style for signals and slots .将您的 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 的评论和回答。)

... connect moved from being an object method to a method acting upon the attribute when PyQt went from 4 to 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:PyQt QTreeview 示例 - 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23993895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com