Qt 监听文件和目录的修改
此文主要介绍Qt中的QFileSystemWatcher类,它主要用于监听文件和目录的修改。
.h文件
```cpp #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFileSystemWatcher> #include <QDebug> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void SaveCameraConfig(QStringList strliConfig); private slots: void on_fileChanged(const QString &path); void on_directoryChanged(const QString &path); void on_pushButton_clicked(); private: Ui::MainWindow *ui; QFileSystemWatcher *m_FileWatcher; QStringList m_listOfConfig; }; #endif // MAINWINDOW_H .cpp文件 #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_FileWatcher = new QFileSystemWatcher(); m_FileWatcher->addPath("F:\\GACII_TM_Control\\TestFile\\cameras"); m_FileWatcher->addPath("F:\\GACII_TM_Control\\TestFile\\"); connect(m_FileWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::on_fileChanged); connect(m_FileWatcher, &QFileSystemWatcher::directoryChanged, this, &MainWindow::on_directoryChanged); } MainWindow::~MainWindow() { delete ui; } void MainWindow::SaveCameraConfig(QStringList strliConfig) { QStringList strList; QString strFileName = "F:\\GACII_TM_Control\\TestFile\\cameras"; QFile file(strFileName); if (file.open(QFile::WriteOnly)) { for (int i = 0; i < strliConfig.size(); i++) { QString str = strliConfig[i] + "\r\n"; file.write(str.toStdString().c_str()); } file.close(); } } void MainWindow::on_directoryChanged(const QString &path) { qDebug() << "目录发生改变--" << path; } void MainWindow::on_fileChanged(const QString &path) { qDebug() << "file发生改变--" << path; } void MainWindow::on_pushButton_clicked() { int num = m_listOfConfig.size(); m_listOfConfig.append(QString::number(num)); SaveCameraConfig(m_listOfConfig); }