SetRootPath未按预期设置工作

2024-04-26 03:10:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了来自这个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

谢谢你的帮助。在


Tags: testimportselfsignalmodelinitmaindef
1条回答
网友
1楼 · 发布于 2024-04-26 03:10:36

您必须向QTreeView指明您的根项是setRootIndex()

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_())

相关问题 更多 >