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

标签 c++ qt qfilesystemwatcher

我在 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.

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

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

最佳答案

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

QFileSystemWatcher *watcher = new QFileSystemWatcher();

关于Windows 上的 C++ Qt 5.0.2 QFileSystemWatcher 看不到目录更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725307/

相关文章:

C++ 静态存储持续时间对象在 main() 之前初始化

c++ - QT检测目录和子文件夹更改

c++ - QFileSystemWatcher::addPath 递归

c++ - 如何将 int 映射到 const char 指针 C++?

c++ - 具有引用模板参数的函数模板

c++ - C++ 中的删除运算符是否需要正确的类型?

c++ - 覆盖 QIODevice 子类中的 readData 返回不正确的结果

c++ - 静态依赖库是否需要包含静态依赖库

qt - 为什么 QML 中文本的宽度/高度和 anchor 冲突?

c++ - 监控文件完整性