C++ 如何使用 QFileSystemWatcher 监视文件夹的更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10044853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:32:18  来源:igfitidea点击:

How to use QFileSystemWatcher to monitor a folder for change

c++qt

提问by Hami

I'm new with QT and I want to use the QFileSystemWatcher to monitor a folder. I just can't figure how to do that.

我是 QT 的新手,我想使用 QFileSystemWatcher 来监视文件夹。我就是不知道该怎么做。

I read http://qt-project.org/doc/qt-4.8/qfilesystemwatcher.htmlbut I don't know how to even initialize it.

我读了http://qt-project.org/doc/qt-4.8/qfilesystemwatcher.html但我什至不知道如何初始化它。

I haven't found a single example, so now, I please if somebody could post an explanation or a simple example that monitors a folder and nothing more.

我还没有找到一个例子,所以现在,如果有人可以发布一个解释或一个简单的例子来监视一个文件夹,仅此而已。

Oh, and this is supposed to run in console if it matters.

哦,如果重要的话,这应该在控制台中运行。

Thx for your answers and regards.

感谢您的回答和问候。

回答by Soumya Kundu

Please have a look at this .h and .cpp , it shows the example... cheers !

请看看这个 .h 和 .cpp ,它显示了示例......干杯!

#ifndef MYCLASS_H
#define MYCLASS_H

#include <QWidget>
#include <QMessageBox>

class MyClass : public QWidget
{
    Q_OBJECT

public:
    MyClass(QWidget* parent=0)
        :QWidget(parent){}

    ~MyClass(){}

public slots:
    void showModified(const QString& str)
    {
        Q_UNUSED(str)
        QMessageBox::information(this,"Directory Modified", "Your Directory is modified");
    }
};

#endif // MYCLASS_H



#include <QApplication>
#include <QFileSystemWatcher>
#include <QDebug>

#include "MyClass.h"

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    QFileSystemWatcher watcher;
    watcher.addPath("C:/QtTest");

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

    MyClass* mc = new MyClass;

    QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), mc, SLOT(showModified(QString)));

    return app.exec();
}

When ever you modify, or create or delete a file or folder within "C:/QtTest" path you will get a message box.

当您在“C:/QtTest”路径中修改、创建或删除文件或文件夹时,您将收到一个消息框。