Monitor File Creation Using QFileSystemModel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import sys

from PySide6.QtCore import QDir
from PySide6.QtWidgets import (QApplication,
    QWidget, QLabel, QVBoxLayout, QFileSystemModel)


class Window(QWidget):
    
    def __init__(self):

        super().__init__()
        
        layout = QVBoxLayout()
        self.setWindowTitle('Monitoring current directory')
        self.setLayout(layout)

        self.label = QLabel('Monitoring file creation')
        layout.addWidget(self.label)
        
        # 1 - Create a QFileSystemModel object.
        #     Set the directory to be monitored
        #     and the filter to monitor files only.
        
        self.model = QFileSystemModel()
        self.model.setRootPath(QDir.currentPath())
        self.model.setFilter(QDir.Filter.Files)
        
        # 3 - Connect QFileSystemModel.rowsInsewrted
        #     with the slot.
        
        self.model.rowsInserted.connect(self.on_rows_inserted)
    
    # 2 - Create the slot
    
    def on_rows_inserted(self, parent, first, last):
        filenames = ''
        for row in range(first, last + 1):
            index = self.model.index(row, 0, parent)
            filenames = filenames + index.data() + '\n'
        self.label.setText(filenames)


if __name__ == '__main__':

    app = QApplication(sys.argv)

    main_window = Window()
    main_window.show()

    sys.exit(app.exec())

The need to monitor file system events - file or directory creation, modification or deletion comes up fairly often. There’s a Qt class named QFileSystemWatcher that lets do this but this class’ directoryChanged signal does not report which file from the monitored directory has triggered it. In the example, instead of QFileSystemWatcher, we (ab)use the QFileSystemModel class whose rowsInserted signal lets us get the created file name. To monitor a directory for file creation

  1. Create a QFileSystemModel object, set its root path to the path of the directory you want to monitor, and add a filter to exclude subdirectories.

  2. Create the slot method to handle the rowsInserted signals. rowsInserted passes the first and the last row that was changed and we use the row numbers to get QModelIndex instances and the changed files names and set the label text to their paths.

  3. Connect the signal and the slot.