1

EDIT2: model.hasChildren(parentIndex)返回True,但model.rowCount(parentIndex)返回0。QFileSystemModel 在 PyQt 中只是 fubar 吗?

编辑:如果我使用 QDirModel,只要稍加调整,这一切都可以正常工作。这已被弃用,但也许 QFileSystemModel 尚未在 PyQt 中完全实现?


我目前正在学习 Qt 模型/视图架构,但我发现有些东西不能像我预期的那样工作。我有以下代码(改编自Qt Model Classes):

from PyQt4 import QtCore, QtGui

model = QtGui.QFileSystemModel()

parentIndex = model.index(QtCore.QDir.currentPath())
print model.isDir(parentIndex) #prints True
print model.data(parentIndex).toString() #prints name of current directory

rows = model.rowCount(parentIndex)
print rows #prints 0 (even though the current directory has directory and file children)

问题:

这是 PyQt 的问题,是我做错了什么,还是我完全误解了 QFileSystemModel?根据文档,model.rowCount(parentIndex)应该返回当前目录中的子节点数。(我在 Ubuntu 下使用 Python 2.6 运行它)

QFileSystemModel 文档说它需要一个 Gui 应用程序的实例,所以我还将上面的代码放在 QWidget 中,如下所示,但结果相同:

import sys
from PyQt4 import QtCore, QtGui

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        model = QtGui.QFileSystemModel()

        parentIndex = model.index(QtCore.QDir.currentPath())
        print model.isDir(parentIndex)
        print model.data(parentIndex).toString()

        rows = model.rowCount(parentIndex)
        print rows


def main():
    app = QtGui.QApplication(sys.argv)
    widget = Widget()
    widget.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
4

2 回答 2

2

我已经解决了。

使用 QFileSystemModel 而不是 QDirModel 的原因是因为 QFileSystemModel 在单独的线程中从文件系统加载数据。这样做的问题是,如果您在构建后尝试打印子节点的数量,那么它还没有加载子节点。修复上述代码的方法是添加以下内容:

self.timer = QtCore.QTimer(self)
self.timer.singleShot(1, self.printRowCount)

到构造函数的末尾,并添加一个 printRowCount 方法,该方法将打印正确数量的子级。呸。

于 2010-04-17T15:59:04.387 回答
1

既然你已经弄明白了,那么对你的模型发生了什么还有一些额外的想法: QFileSystemModel::rowCount 从 visibleChildren 集合中返回行;我想您已经正确识别了问题:在您检查行数时,它尚未填充。我在不使用计时器的情况下更改了您的示例;请检查它是否适合您:

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.model = QtGui.QFileSystemModel()
        self.model.setRootPath(QtCore.QDir.currentPath())

    def checkParent(self):
        parentIndex = self.model.index(QtCore.QDir.currentPath())      

        print self.model.isDir(parentIndex)
        print self.model.data(parentIndex).toString()

        rows = self.model.rowCount(parentIndex)
        print "row count:", rows

def main():
    app = QtGui.QApplication(sys.argv)
    widget = Widget()
    widget.show()
    app.processEvents(QtCore.QEventLoop.AllEvents)  
    widget.checkParent()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

我相信在屏幕上显示构建的小部件后,您的代码应该在任何 UI 事件上都能正常工作

问候

于 2010-04-17T16:33:57.600 回答