用QFileSystemWatcher实现简易的文件监控程序

QFileSystemWatcher类用于监控文件或目录的变化

--当文件或目录发生变化时触发信号

--通过信号与槽机制捕捉触发信号

代码如下:

//main.cpp

#include <QtCore/QCoreApplication>

#include "Watcher.h"

int main(int argc, char *argv[])

{

    QCoreApplication a(argc, argv);

    Watcher watcher;

    watcher.addPath("C:/Users/hp/Desktop/text.txt");

    watcher.addPath("C:/Users/hp/Desktop/QDir");

    

    return a.exec();

}

//Watcher.h

#ifndef _WATCHER_H_

#define _WATCHER_H_

#include <QObject>

#include <QFileSystemWatcher>

class Watcher : public QObject

{

    Q_OBJECT

    QFileSystemWatcher m_watcher;

private slots:

    void statusChanged(const QString& path);

public:

    explicit Watcher(QObject *parent = 0); //C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生,声明为explicit的构造函数不能在隐式转换中使用。

    void addPath(QString path);

};

#endif // WATCHER_H

//Watcher.cpp

#include "Watcher.h"

#include <QDebug>

Watcher::Watcher(QObject *parent) : QObject(parent)

{

    connect(&m_watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(statusChanged(const QString&)));          //信号与槽机制捕捉文件改变信号

    connect(&m_watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(statusChanged(const QString&)));

}

void Watcher::statusChanged(const QString &path)

{

    qDebug() << path << "is changed!";

}

void Watcher::addPath(QString path)   //添加要监控的文件路径,可有多个

{

    m_watcher.addPath(path);

}

//文章参考狄泰软件学院Qt视频教程

猜你喜欢

转载自blog.csdn.net/qq_37182906/article/details/84933693