[英]PySide2 - Program crashes when calling QFileSystemModel.index()
I am trying to convert into Python the following C++ example from https://doc.qt.io/qt-5/model-view-programming.html#using-model-indexes :我正在尝试将https://doc.qt.io/qt-5/model-view-programming.html#using-model-indexes 中的以下 C++ 示例转换为 Python:
C++: C++:
QFileSystemModel *model = new QFileSystemModel;
QModelIndex parentIndex = model->index(QDir::currentPath());
int numRows = model->rowCount(parentIndex);
Python: Python:
import os
from PySide2.QtWidgets import *
model = QFileSystemModel()
parent_index = model.index(os.getcwd())
nb_row = model.rowCount(parent_index)
print(nb_row)
but my progam crashes with exit code :但我的程序因退出代码而崩溃:
Process finished with exit code -1073741819 (0xC0000005)
If you run the code in a CMD/console you will get the following error message:如果您在 CMD/控制台中运行代码,您将收到以下错误消息:
QSocketNotifier: Can only be used with threads started with QThread
Segmentation fault (core dumped)
Which indicates that QFileSystemModel
uses a QThread (that is also indicated in the docs ), and for a QThread to run it needs an event loop, in this case you must create an instance of QApplication
:这表明
QFileSystemModel
使用 QThread (也在docs 中指出),并且 QThread 运行它需要一个事件循环,在这种情况下,您必须创建QApplication
的实例:
import os
import sys
from PySide2.QtWidgets import QApplication, QFileSystemModel
if __name__ == "__main__":
app = QApplication(sys.argv)
model = QFileSystemModel()
parent_index = model.index(os.getcwd())
nb_row = model.rowCount(parent_index)
print(nb_row)
The above is also explicitly indicated in the docs :文档中也明确指出了上述内容:
Detailed Description
详细说明
This class provides access to the local filesystem, providing functions for renaming and removing files and directories, and for creating new directories.
此类提供对本地文件系统的访问,提供重命名和删除文件和目录以及创建新目录的功能。 In the simplest case, it can be used with a suitable display widget as part of a browser or filter.
在最简单的情况下,它可以与合适的显示小部件一起使用,作为浏览器或过滤器的一部分。
QFileSystemModel can be accessed using the standard interface provided by QAbstractItemModel, but it also provides some convenience functions that are specific to a directory model.
QFileSystemModel 可以使用 QAbstractItemModel 提供的标准接口进行访问,但它也提供了一些特定于目录模型的便利功能。 The fileInfo(), isDir(), fileName() and filePath() functions provide information about the underlying files and directories related to items in the model.
fileInfo()、isDir()、fileName() 和 filePath() 函数提供有关与模型中的项目相关的基础文件和目录的信息。 Directories can be created and removed using mkdir(), rmdir().
可以使用 mkdir()、rmdir() 创建和删除目录。
Note: QFileSystemModel requires an instance of QApplication.
注意:QFileSystemModel 需要一个 QApplication 的实例。
(emphasis mine) (强调我的)
In the case of C++, QApplication was probably created in the main.cpp.在 C++ 的情况下,QApplication 可能是在 main.cpp 中创建的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.