PySide2 - Program crashes when calling QFileSystemModel.index()

1

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 :

C++:

QFileSystemModel *model = new QFileSystemModel;
QModelIndex parentIndex = model->index(QDir::currentPath());
int numRows = model->rowCount(parentIndex);

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)
python
indexing
pyside2
qfilesystemmodel
asked on Stack Overflow Nov 28, 2019 by u2gilles

1 Answer

1

If you run the code in a CMD/console you will get the following error message:

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:

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. The fileInfo(), isDir(), fileName() and filePath() functions provide information about the underlying files and directories related to items in the model. Directories can be created and removed using mkdir(), rmdir().

Note: QFileSystemModel requires an instance of QApplication.

(emphasis mine)

In the case of C++, QApplication was probably created in the main.cpp.

answered on Stack Overflow Nov 28, 2019 by eyllanesc

User contributions licensed under CC BY-SA 3.0