Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

c++ - How to use QFileSystemWatcher to monitor a folder for change

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.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

#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 <<"
";

    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...