使用QFileSystemWatcher监视文件目录变化

使用QFileSystemWatcher类用于监视文件和目录的修改。

使用方法

  1. 添加需要监视的文件或目录

    1
    2
    bool addPath(const QString &path);
    QStringList addPaths(const QStringList &paths);
  2. 监听信号的变化

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

示例

  • MyFileWatcher.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #ifndef MYFILEWATCHER_H
    #define MYFILEWATCHER_H

    #include <QObject>
    #include <QFileSystemWatcher>

    class MyFileWatcher : public QObject
    {
    Q_OBJECT
    public:
    explicit MyFileWatcher(QObject *parent = nullptr);

    public slots:
    void onFileChanged(const QString &file);
    void onDirectoryChanged(const QString &path);

    private:
    QFileSystemWatcher m_fileWatcher;
    };

    #endif // MYFILEWATCHER_H
  • MyFileWatcher.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #include "MyFileWatcher.h"
    #include <QDebug>

    MyFileWatcher::MyFileWatcher(QObject *parent) : QObject(parent)
    {
    m_fileWatcher.addPath("C:/Documents/test.txt"); // monitoring file
    m_fileWatcher.addPath("C:/Documents/test"); // monitoring directory

    connect(&m_fileWatcher, SIGNAL(fileChanged(const QString&)), this, SLOT(onFileChanged(const QString &)));
    connect(&m_fileWatcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(onDirectoryChanged(const QString &)));

    qDebug()<<"Monitoring File:"<<m_fileWatcher.files();
    qDebug()<<"Monitoring Directory:"<<m_fileWatcher.directories();
    }

    void MyFileWatcher::onFileChanged(const QString &file)
    {
    qDebug()<<"File Changed:"<<file;
    }

    void MyFileWatcher::onDirectoryChanged(const QString &path)
    {
    qDebug()<<"Directory Changed:"<<path;
    }