10

I was trying the QFileSystemWatcher out and it somehow doesn't work as expected. Or am I doing something wrong?

I've set the QFileSystemWatcher to watch a single file. When I modify the file for the first time, fileChanged() gets emited, that's OK. But when I modify the file again, fileChanged() doesn't get emited anymore.

Here is the source code:

main.cpp

#include <QApplication>

#include "mainwindow.h"

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  MainWindow window;

  window.show();

  return app.exec();
}

mainwindow.h

#include <QDebug>
#include <QFileSystemWatcher>
#include <QMainWindow>
#include <QString>

class MainWindow : public QMainWindow
{
  Q_OBJECT

public:

  MainWindow();

private slots:

  void directoryChanged(const QString & path);
  void fileChanged(const QString & path);

private:

  QFileSystemWatcher * watcher;
};

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow()
{
  watcher = new QFileSystemWatcher(this);
  connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &)));
  connect(watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(directoryChanged(const QString &)));
  watcher->addPath("path to directory");
  watcher->addPath("path to file");
}

void MainWindow::directoryChanged(const QString & path)
{
  qDebug() << path;
}

void MainWindow::fileChanged(const QString & path)
{
  qDebug() << path;
}

Thank you for your answers.

Edit 1

I ran this code under Linux.

Edit 2

I actually need to check all MetaPost files in a tree given by some directory, whether they were modified. I will probably stick to my alternative solution, which is to run QTimer every second and manually check all files. The QFileSystemWatcher probably does this in similar fashion internally, but probably more effectively.

4

3 回答 3

14

刚才遇到了同样的问题。似乎 QFileSystemWatcher 认为文件被删除,即使它只是被修改。至少在Linux文件系统上。我的简单解决方案是:

if (QFile::exists(path)) {
    watcher->addPath(path);
}

将以上内容添加到您的fileChanged(). 根据需要更改单词watcher

于 2013-08-18T23:04:11.583 回答
13

我在 Linux 上使用 Qt5 时遇到了同样的问题。找出原因:

一些文本编辑器,如 kate,不会修改文件的内容,而是用新文件替换原始文件。替换文件将删除旧文件(IN_DELETE_SELF事件),因此 qt 将停止查看文件。

一种解决方案是还监视文件目录中的创建事件。

于 2015-05-06T12:01:14.483 回答
4

我可以确认您对当前 Qt5 和 Linux 的问题。除了 Peter 给出的答案之外,我还通过在 slot-function 的末尾添加以下代码来解决这个问题:

QFileInfo checkFile(path);
while(!checkFile.exists())
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
watcher->addPath(path);

请注意,如果您立即添加路径,该文件通常还不存在,您会收到警告并且根本不会添加任何内容,并且观察者会丢失此路径。因此,您必须等待/睡眠,直到文件再次恢复正常,然后添加它。

另请注意,在此示例中,我使用了 C++11 并包含 and 来实现睡眠。

于 2014-11-27T12:17:14.897 回答