gpt4 book ai didi

python - 我的 QFileSystemModel 在 PyQt 中无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 23:59:02 27 4
gpt4 key购买 nike

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

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

<小时/>

我现在正在学习 Qt 模型/ View 架构,但我发现一些东西并不像我期望的那样工作。我有以下代码(改编自 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()

最佳答案

我已经解决了。

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

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

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

关于python - 我的 QFileSystemModel 在 PyQt 中无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2658467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com