This is the development based on my question here

My problem now is that I can't get the signal directoryChanged of the class QFileSystemWatcher to work with the slot in the thread where QFileSystemWatcher is created. Following is the code:
Any help with getting it to work correctly (catch the signal) will be greatly appreciated.
Thanks!

Qt Code:
  1. class threadedScraper : public QThread
  2. {
  3. Q_OBJECT
  4. int _id;
  5. QMutex& _mtx;
  6. QString _path;
  7. QFileSystemWatcher* _filesystemwatcher;
  8. void run() override
  9. {
  10. _filesystemwatcher = new QFileSystemWatcher();
  11. _filesystemwatcher->moveToThread(this);
  12. _filesystemwatcher->addPath(_path);
  13.  
  14. // I tried different connection types. Qt::ConnectionType::DirectConnection does not work either
  15. if (! connect(_filesystemwatcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(ondirectoryChanged(const QString&))))
  16. {
  17. qDebug() << "failure to connect to QFileSystemWatcher::directoryChanged signal";
  18. return;
  19. }
  20.  
  21. qDebug() << QString("cycle %1: waiting for file creation in %2").arg(_id).arg(_path);
  22. exec();
  23. qDebug() << QString("cycle %1: stopped waiting for file").arg(_id);
  24. }
  25. private slots:
  26. void ondirectoryChanged (const QString& p)
  27. {
  28. qDebug() << "cycle:" << QString::number(_id) << "file:" <<p;
  29. _mtx.unlock();
  30. }
  31. public:
  32. threadedScraper(int id, QMutex& m, QString p) : _id(id), _mtx(m), _path(p), _filesystemwatcher(nullptr), QThread()
  33. {
  34. }
  35. virtual ~threadedScraper()
  36. {
  37. if (_filesystemwatcher != nullptr)
  38. delete _filesystemwatcher;
  39. }
  40. };
  41.  
  42. int main(int argc, char *argv[])
  43. {
  44. QCoreApplication a(argc, argv);
  45.  
  46. QMutex mtx;
  47. QString directoryToMonitor="c:/temp/files";
  48.  
  49. QTimer::singleShot(2000,&a, [&](){
  50. qDebug()<< "started scraping";
  51. for (int i = 0; i < 2; ++i) {
  52. qDebug() << "starting cycle " << QString::number(i);
  53. threadedScraper worker (i, mtx, directoryToMonitor);
  54. worker.start();
  55. mtx.lock();
  56. wc.wait(&mtx, 5000); // I need to wait until the file is found in the monitoring directory or 5 seconds elapsed
  57. worker.exit(0); // stop the thread
  58. worker.wait();
  59. mtx.unlock();
  60. }
  61. qDebug()<< "finished scraping";
  62. });
  63. return a.exec();
  64. }
To copy to clipboard, switch view to plain text mode