I am a little bit blown away with some result I obtained. I dont know what I am missing regarding the Qt library or python itself. I want to count the lines of my model, I have this code snippet which works, but sometimes the rows are properly retrieved and other times (in the init method and the program itself) 0 is obtained. What is wrong with this?
Find my working code snippet (based on: pyqt QFileSystemModel rowCount):
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QSplitter, QTreeView, QListView, QMainWindow, QFrame
from PyQt5.QtCore import QTimer
import sys
class TestWindow(QSplitter):
def __init__(self):
QFrame.__init__(self)
# self.splitter = QSplitter()
self.model = QFileSystemModel()
# model.setRootPath(QDir.currentPath())
self.parentIndex = self.model.setRootPath("C:/Users/Luis/Documents/python/pyqt5")
self.treeView = QTreeView(self)
self.treeView.setModel(self.model)
# tree.setRootIndex(model.index(QDir.currentPath()))
self.treeView.setRootIndex(self.model.index("C:/Users/Luis/Documents/python/pyqt5"))
self.listView = QListView(self)
self.listView.setModel(self.model)
# list.setRootIndex(model.index(QDir.currentPath()))
self.listView.setRootIndex(self.model.index("C:/Users/Luis/Documents/python/pyqt5"))
print('in the init method: ', self.model.rowCount(self.parentIndex))
self.setWindowTitle("Two views onto the same directory model")
# self.splitter.show()
self.model.directoryLoaded.connect(self._loaded)
QTimer.singleShot(10000, self._really_loaded)
def _loaded(self):
print('_loaded', self.model.rowCount(self.parentIndex))
def _really_loaded(self):
print('_really_loaded', self.model.rowCount(self.parentIndex))
if __name__ == '__main__':
app = QApplication(sys.argv)
test = TestWindow()
print('before showing the app', test.model.rowCount(test.parentIndex))
test.show()
print('after showing app', test.model.rowCount(test.parentIndex))
sys.exit(app.exec_())
And my output:
You can put a working path of yours instead of mine to try out the code. I expected to obtain the number of rows of the model wherever it was asked in the code. Why sometimes its 0? Thanks for your comments.