Windows上的C ++ Qt 5.0.2 QFileSystemWatcher没有看到目录更改

时间:2013-05-23 23:05:37

标签: c++ qt qfilesystemwatcher

我在Windows上的Qt 5.0.2中遇到了QFileSystemWatcher的问题。

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;
}

我遇到的问题是,即使我在“C:/ data / watch”文件夹中创建/移动/编辑文件,也不会调用“showModified”或“showChanged”函数,即使他们有

我确定插槽的名称是正确的,因为如果我将插槽的名称更改为不存在的插槽的名称,则会收到错误:

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

我也确定我作为路径添加的目录存在,因为在进行列表时:

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

我得到了我的目录:

Directory name "C:/data/watch" 

并且文档明确指出:(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.

很明显我错过了一些东西。 如果有人可以指出我的错误,或者甚至可以提供另一种方案来解决我的问题,我将不胜感激。

非常感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

您似乎在堆栈内存上分配了QFileSystemWatcher对象,因此在您创建对象的函数结束后,您的对象将被销毁。所以请改用它:

QFileSystemWatcher *watcher = new QFileSystemWatcher();