我使用了此 post 中的部分代码(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_())
我对这条线有疑问
model.setRootPath('C:\')
当我运行该程序时,它总是显示类似 C: D: 的驱动器,只是不是 C:\的内容,或者即使我输入“C:\Users\”或什至不存在的路径,它总是只是显示,请参阅附图,我做错了什么?
显示文件管理器的 PyQt 程序图像
我正在使用: Windows 10, 皮查姆, Python 3.5, PyQt5,
感谢您的帮助。
最佳答案
您必须使用 setRootIndex()
向 QTreeView
指示您的根项目是什么:
from PyQt5.QtCore import QDir
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication
class Main(QTreeView):
def __init__(self):
QTreeView.__init__(self)
model = QFileSystemModel()
self.setModel(model)
model.setRootPath(QDir.rootPath())
self.setRootIndex(model.index("C:"))
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 - SetRootPath 未按预期设置工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617149/