【问题标题】:C++ Qt 5.0.2 QFileSystemWatcher on Windows not seeing directory changesWindows 上的 C++ Qt 5.0.2 QFileSystemWatcher 看不到目录更改
【发布时间】:2013-05-23 23:05:37
【问题描述】:

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

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

您的帮助将不胜感激。谢谢。

【问题讨论】:

    标签: c++ qt qfilesystemwatcher


    【解决方案1】:

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

    QFileSystemWatcher *watcher = new QFileSystemWatcher();
    

    【讨论】:

    • 成功了,非常感谢!!!因此,要将信号连接到插槽,我需要传递包含对象的取消引用变量。对吗?
    • @TrevorDonahue 您所做的是正确的,信号和插槽连接确实有效。问题是您的 QFileSystemWatcher 在您创建它的功能完成后立即被删除。如果它在你的函数完成之前发出一个信号,你连接到它的插槽将被调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    相关资源
    最近更新 更多