如预期中的PyQt我QFileSystemModel不起作用
-
27-09-2019 - |
题
<强> EDIT2:强> model.hasChildren(parentIndex)
返回True
,但model.rowCount(parentIndex)
返回0
。是QFileSystemModel只是FUBAR在PyQt的?
编辑:。通过有点适应这一切工作,正是因为它应该,如果我使用QDirModel。这已被弃用,但也许QFileSystemModel尚未在PyQt的得到充分执行?
我学习的那一刻Qt的模型/视图架构,我发现的东西,不工作,因为我希望它。我有以下代码(摘自 Qt的模型类):
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方法。呼。
其他提示
既然你已经想通了,只是一对夫妇的上发生了什么事情与您的模型额外的想法:从visibleChildren收集QFileSystemModel :: rowCount时返回行;我猜你正确识别的问题:在当你检查行的时间算它尚未填充。我已经改变了你的榜样,而无需使用计时器;请,检查它是否适合你:
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事件正常工作后插件构成被示出在屏幕上
问候