I am trying to use QFileSystemWatcher like in the following example : How to use QFileSystemWatcher to monitor a folder for change My issue is that the watcher does work when I create it in the main() function like in the following :
#include "mainwindow.h"
#include <QApplication>
#include <QFileSystemWatcher>
#include <QDebug>
#include "systemfilewatcher.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileSystemWatcher watcher;
watcher.addPath("C:/QtTest");
SystemFileWatcher* mc = new SystemFileWatcher();
QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), mc,
SLOT(showModified(QString)));
MainWindow w(&watcher);
w.show();
return a.exec();
}
however when I try this exact same code in my ui like in the following, it doesn't work :
MainWindow::MainWindow(QFileSystemWatcher folder, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFileSystemWatcher watcher;
watcher.addPath("C:/QtTest");
SystemFileWatcher* mc = new SystemFileWatcher();
QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), mc, SLOT(showModified(QString)));
this is my "systemfilewatcher.h" :
#ifndef SYSTEMFILEWATCHER
#define SYSTEMFILEWATCHER
#include <QWidget>
#include <QMessageBox>
class SystemFileWatcher : public QWidget
{
Q_OBJECT
public:
SystemFileWatcher(QWidget* parent=0)
:QWidget(parent){}
~SystemFileWatcher(){}
public slots:
void showModified(const QString& str)
{
QMessageBox::information(this,"Directory Modified", str);
}
};
#endif // SYSTEMFILEWATCHER
}
My goal is to detect when a file is created in a targeted directory and put its name in a QString stack. I don't know what I am doing wrong here, could someone help me please ?
In the second case, your QFileSystemWatcher watcher
is created on the stack and is destroyed as soon as the constructor ends. You have to keep a reference to it somewhere, possibly as an attribute of your SystemFileWatcher
class