python - SetRootPath 未按预期设置工作

标签 python pyqt pyqt5 qtreeview qfilesystemmodel

我使用了此 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/

相关文章:

python - 比较并连接两个数据框中的两列

python - Django 密码重置

qt - Qt拖放中的热点是什么意思?

python - 使用 moveToThread 在 PyQt5 中启动 QThreads。一个线程无法正常启动

python - QtableView单元格在窗体关闭时失去焦点时如何保存正在编辑的数据

c# - QuickFix C# 或 Python

python - 在一个散点图中绘制两个 pandas 数据框

python - qlabel 不能触发鼠标释放事件

python - 使用 PyQt5 运行命令并获取 stdout 和 stderr

python 应用程序在 thread.join() 上卡住