使用QFileSystemWatcher类用于监视文件和目录的修改。
使用方法
添加需要监视的文件或目录
1
2bool addPath(const QString &path);
QStringList addPaths(const QStringList &paths);监听信号的变化
1
2void 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
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;
};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
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;
}