Qt 中directoryChanged监听某个目录的内容是否发生变化

发布于:2025-06-12 ⋅ 阅读:(15) ⋅ 点赞:(0)
  • Qt 中,directoryChanged 是 QFileSystemWatcher 类的一个信号,用于监听某个目录的内容是否发生变化(如添加、删除文件或子目录)

✅ 一、功能说明

  • QFileSystemWatcher::directoryChanged(const QString &path) 信号的作用是:
  • 当你监视的目录内容发生变化时,会发出这个信号。
  • 比如: 新增文件/文件夹 删除文件/文件 重命名文件/文件夹

✅ 二、使用方法

filewatcher.h

#ifndef FILEWATCHER_H
#define FILEWATCHER_H

#include <QObject>
#include <QStringList>
#include <QFileSystemWatcher>

class FileWatcher : public QObject
{
    Q_OBJECT
public:
    explicit FileWatcher(const QString &dirPath, QObject *parent = 0);

private slots:
    void onDirectoryChanged(const QString &path);

private:
    QFileSystemWatcher *watcher;
    QString watchDir;
    QStringList currentFiles;

    void updateFileList();
};

#endif // FILEWATCHER_H

#include "filewatcher.h"
#include <QDir>
#include <QMessageBox>
#include <QDebug>

FileWatcher::FileWatcher(const QString &dirPath, QObject *parent)
    : QObject(parent), watchDir(dirPath)
{
    watcher = new QFileSystemWatcher(this);

    if (QDir(watchDir).exists()) {
        watcher->addPath(watchDir);
        updateFileList();
        connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(onDirectoryChanged(QString)));
    } else {
        qDebug() << "目录不存在: " << dirPath;
    }
}

void FileWatcher::updateFileList()
{
    QDir dir(watchDir);
    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    currentFiles = dir.entryList(); // 保存当前文件列表
}

void FileWatcher::onDirectoryChanged(const QString &path)
{
    QDir dir(path);
    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    QStringList newFileList = dir.entryList();

    // 找出被删除的文件
    QStringList deletedFiles;
    foreach (QString file, currentFiles) {
        if (!newFileList.contains(file)) {
            deletedFiles << file;
        }
    }

    if (!deletedFiles.isEmpty()) {
        QString msg = QString::fromLocal8Bit("以下文件被删除:\n") + deletedFiles.join("\n");
        QMessageBox::warning(0, QString::fromLocal8Bit("文件删除警告"), msg);
    }

    // 更新当前文件列表
    currentFiles = newFileList;
}

✅ 三、注意事项

  1. 只能监控一级内容变化
    它 不会递归 监控子目录变化,除非你手动为每个子目录也调用 addPath()。

如果你需要递归监听,需要手动遍历子目录并添加到监控列表。