pyqt QFileSystemModel行计数

2024-09-25 14:16:29 发布

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

我看过一些关于QFileSystemModel行数不能按预期工作的帖子(ex1ex2),但我似乎遗漏了一些东西。以下代码始终报告行计数为1,即使在等待10秒后,列表显示的行数更多。我错过了什么?在

import os, sys
from PyQt5 import QtWidgets, QtCore


class TestWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.model = QtWidgets.QFileSystemModel()
        self.model.setFilter(QtCore.QDir.AllEntries | QtCore.QDir.Hidden | QtCore.QDir.NoDot)
        self.path = os.path.expanduser('~')
        self.model.setRootPath(self.path)
        view = QtWidgets.QListView()
        view.setModel(self.model)
        view.setRootIndex(self.model.index(self.path))
        self.setCentralWidget(view)
        self.model.directoryLoaded.connect(self._loaded)
        QtCore.QTimer.singleShot(10000, self._really_loaded)

    def _loaded(self):
        print('_loaded', self.path, self.model.rowCount())  # Always returns 1 here? even though there are more rows displayed

    def _really_loaded(self):
        print('_really_loaded', self.path, self.model.rowCount())  # 10 seconds later...Always returns 1 here? even tho there are more rows displayed


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    test = TestWindow()
    test.show()
    sys.exit(app.exec_())

…和Pyqty的结果一样

^{pr2}$

Tags: pathimportselfviewmodelosdefsys
1条回答
网友
1楼 · 发布于 2024-09-25 14:16:29

必须传递要分析的项的索引,如果要知道有多少项,请使用返回setRootPath()的索引。

import os, sys
from PyQt5 import QtWidgets, QtCore


class TestWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.model = QtWidgets.QFileSystemModel()
        self.model.setFilter(QtCore.QDir.AllEntries | QtCore.QDir.Hidden | QtCore.QDir.NoDot)
        self.path = os.path.expanduser('~')
        self.parentIndex  = self.model.setRootPath(self.path)
        view = QtWidgets.QListView()
        view.setModel(self.model)
        view.setRootIndex(self.model.index(self.path))
        self.setCentralWidget(view)
        self.model.directoryLoaded.connect(self._loaded)
        QtCore.QTimer.singleShot(10000, self._really_loaded)

    def _loaded(self, path):
        print('_loaded', self.path, self.model.rowCount(self.parentIndex))  # Always returns 1 here? even though there are more rows displayed

    def _really_loaded(self):
        print('_really_loaded', self.path, self.model.rowCount(self.parentIndex))  # 10 seconds later...Always returns 1 here? even tho there are more rows displayed


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    test = TestWindow()
    test.show()
    sys.exit(app.exec_())

相关问题 更多 >