0

我对 Windows 上 Qt 5.0.2 的 QFileSystemWatcher 有疑问。

测试.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.

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

对你的帮助表示感谢。谢谢你。

4

1 回答 1

2

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

QFileSystemWatcher *watcher = new QFileSystemWatcher();
于 2013-05-24T06:34:13.897 回答