Question

I have a program which relies on the files that are added to a folder. No file can be unregistred, even if the user adds MANY (>200) files to this folder.

When a signal from QFileWatcher is received I'm reading and creating an image out of some of the data, and the execution of this can take up to a few seconds. Both the QFileWatcher and the function that handles the signals resides in the same class. I'm worried that the class might be busy at times and potentially cause QFileWatcher not to register some files.

Should I add QFileWatcher to a thread to ensure the registration of data?

What I'm doing as of now

In main.cpp:

...
MainWindow w;
w.setupFolderMonitoring();
...

In mainwindow.h:

...
public:
  void setupFolderMonitoring();
  void detectFolderChanges();
private:
  QString monitoredPath;
  QFileSystemWatcher watcher;
...

In mainwindow.cpp:

...
void MainWindow::setupFolderMonitoring() {
    watcher.addPath(monitoredPath);
    QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), this, 
    SLOT(detectFolderChanges()));
}
void MainWindow::detectFolderChanges() {
    qDebug() << "Dir was changed";
}
...
Was it helpful?

Solution

In general if your data processing can take longer than a second, you should probably not be doing it on the main thread in order to avoid non-responsive GUI.

Furthermore, when working on folder monitoring in Windows, I observed that the Windows file-monitoring mechanism will start dropping events if the monitoring thread is busy processing data. So that's another good reason to move data processing to it's own thread.

The approach I've taken before was to create a data processing QObject, "move" it to a new thread (using QObject::moveToThread(...)) and connecting it to the filesystem monitor and the GUI using signals and slots.

To be entirely honest, I did not use Qt's filesystem monitoring because I needed more info than Qt provides for file rename events. So I had to use the Windows filesystem monitoring API directly. But I don't think Qt can work around limitations in the OS in terms of processing large-scale changes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top