Question

I have an issue with QFileSystemWatcher from Qt 5.0.2 on Windows.

test.cpp

...
QFileSystemWatcher watcher;
watcher.addPath("C:/data/watch");

QStringList directoryList = watcher.directories();
Q_FOREACH(QString directory, directoryList)
    qDebug() << "Directory name" << directory <<"\n";

DirectoryWatcher* dw = new DirectoryWatcher;

QObject::connect(
    &watcher, SIGNAL(directoryChanged(const QString&)),
    dw,       SLOT(showModified(const QString&))
);

QObject::connect(
    &watcher, SIGNAL(fileChanged(QString)),
    dw,       SLOT(showChanged(QString))
);

DirectoryWatcher.cpp

DirectoryWatcher::DirectoryWatcher(QWidget* parent) : QWidget(parent)
{
    qDebug() << "monitoring" << endl;
}

void DirectoryWatcher::showModified(const QString& str) {
    qDebug() << "Sending File" << str << endl;
}

void DirectoryWatcher::showChanged(const QString& str) {
    qDebug() << "show changed " << str << endl;
}

The problem I'm running into is that even when I'm creating/moving/editing a file into the "C:/data/watch" folder, the functions "showModified" or "showChanged" won't be called, even though they have

I'm sure that the names of the slots are correct, because if I change the names of the slots that go as parameters to non existent ones I receive an error:

QObject::connect: No such slot DirectoryWatcher::showChangeds(QString) (kernel\qobject.cpp:2082, void err_method_notfound(const QObject*, const char*, const char*))

I am also sure that the directory I'm adding as the path exists, because when doing the listing:

QStringList directoryList = watcher.directories();
Q_FOREACH(QString directory, directoryList)
    qDebug() << "Directory name" << directory <<"\n";

I get my directory:

Directory name "C:/data/watch" 

and the documentation clearly states: (http://qt-project.org/doc/qt-5.0/qtcore/qfilesystemwatcher.html#addPath)

Adds path to the file system watcher if path exists. The path is not added if it does not exist, or if it is already being monitored by the file system watcher.

So clearly I'm missing something. It would be greatly appreciated if someone could point where my mistake is, or maybe even give another solution to solve my problem.

Your help will be greatly appreciated. Thank you.

Was it helpful?

Solution

You seem to be allocating your QFileSystemWatcher object on stack memory, so after your function where you create your object ends, your object will get destroyed. So use this instead:

QFileSystemWatcher *watcher = new QFileSystemWatcher();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top