-1

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 ?

Community
  • 1
  • 1
Vince
  • 36
  • 1
  • 4
  • This question amounts to a trivial mistake due to a misunderstanding of object lifetime in C++. The particular combination of that problem and Qt isn't useful to others, thus I vote to close - there's way too many incarnations of the very same problem on SO. – Kuba hasn't forgotten Monica Feb 15 '15 at 20:12

1 Answers1

1

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

Smasho
  • 1,170
  • 8
  • 19
  • Solved my problem by changing this line : QFileSystemWatcher watcher(); by this : QFileSystemWatcher *watcher = new QFileSystemWatcher(); Thanks for your help. – Vince Feb 12 '15 at 03:59
  • 1
    Watch out, doing that without mantaining a reference to the object you wont be able to destroy it, you get a memory leak – Smasho Feb 12 '15 at 04:04
  • @Smasho not in Qt, if the instance is a QObject-derived – Valentin H Sep 14 '15 at 13:20