QT 檔案監視系統QFileSystemWatcher監視目錄的改變
- 相關操作說明
- mainwindow.h
- mainwindow.cpp
- 調試結果
相關操作說明
添加頭檔案
Header:
#include
qmake:
QT += core
如果路徑存在,則會向檔案系統螢幕添加路徑。如果該路徑不存在,或者該路徑已被檔案系統螢幕監視,則不會添加該路徑。
如果路徑指定了一個目錄,則當修改或從磁盤中删除路徑時,将發出目錄更改的directoryChanged()信号;
否則,當修改、重命名或删除路徑時,将發出檔案化的fileChanged()信号。
傳回應用程式的目前目錄的絕對路徑。
建立一個名為目錄名的子目錄。
成功時傳回true;否則将傳回false。如果在調用此函數時該目錄已經存在,則它将傳回false。
returns the path. this may contain symbolic links, but never contains redundant “.”, “…” or multiple separators.
傳回該路徑。這可能包含符号連結,但從不包含備援
"."
;,
".."
或多個分隔符。
當修改指定路徑上的目錄(例如,添加或删除檔案)或從磁盤中删除時,就會發出此信号。請注意,如果在短時間内發生了多個更改,則某些更改可能不會發出此信号。然而,變化序列中的最後一個變化總是會産生這個信号。
注意
:這是一個私人信号。它可以用于信号連接配接,但不能由使用者發出。
當将指定路徑上的檔案從磁盤中進行修改、重命名或删除時,就會發出此信号。
注意:作為一種安全措施,許多應用程式通過編寫一個新檔案,然後删除一個舊檔案來儲存一個打開的檔案。在插槽函數中,您可以檢查watcher.files().contains(路徑)。如果它傳回false,請檢查該檔案是否仍然存在,然後調用添加路徑()以繼續監視它。
注意
:這是一個私人信号。它可以用于信号連接配接,但不能由使用者發出。
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QFile>
#include <QFileSystemWatcher>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>
#include <QApplication>
#include <QDateTime>
#include <QDir>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void DirChanged( QString path);
void FileChanged(QString filename);
private:
QFileSystemWatcher filewatcher;//檔案系統監視對象
QLabel *label;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QStringList list = qApp->arguments();//擷取行參數
qDebug()<<"\nlist = "<<list.size();
for (int i=0;i<list.size();i++) {
qDebug()<<"i="<<i<<"list = "<<list.at(i);
}
QString strpath;
if(list.count() > 1)
strpath = list.at(1);
else
strpath = QDir::currentPath();//目前工程路徑
qDebug()<<"\nstrpath = "<<strpath;
label = new QLabel(this);
label->setFixedSize(100,100);
label->setWordWrap(true);
label->setText(tr("監視目錄為:\n")+strpath);
this->setFixedSize(QSize(500,500));
filewatcher.addPath(strpath); //添加系統監控路徑
QDir dir;
dir.cd(QDir::currentPath()); //進入目前目錄
dir.mkdir("ddd"); //建立檔案夾
//dir.cdUp(); //進入上一級目錄
qDebug()<<"path = "<<dir.path();
QFile file;
file.setFileName(QDir::currentPath()+"/ddd/"+"w.txt");//在ddd/建立文本檔案
bool isopen = file.open(QIODevice::WriteOnly | QIODevice::Text);
if(!isopen)
{
qDebug()<<"檔案打開失敗";
return;
}
filewatcher.addPath(file.fileName());
connect(&filewatcher,SIGNAL(directoryChanged( QString)),this,SLOT(DirChanged( QString)));
connect(&filewatcher,SIGNAL(fileChanged( QString)),this,SLOT(FileChanged( QString)));
}
MainWindow::~MainWindow()
{
}
//建立目錄 或者 建立目錄等會監控到彈出警告框
void MainWindow::DirChanged(QString path)
{
qDebug()<<"path = "<<path;//目前目錄路徑
QMessageBox::warning(NULL,"系統監控目錄變化",path);
}
//當修改、重命名或删除檔案時
void MainWindow::FileChanged(QString filename)
{
qDebug()<<"filename = "<<filename;//目前目錄路徑
QMessageBox::critical(NULL,"系統監控目錄文本檔案變化",filename);
}
調試結果
修改目錄 删除 重命名等
修改檔案 删除 重命名等