#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
// 进行文件系统监视器的信号和槽的关联
connect(&m_fileSysWatcher, SIGNAL(directoryChanged(QString)),this,SLOT(showMessageDir(QString)));
connect(&m_fileSysWatcher, SIGNAL(fileChanged(QString)),this,SLOT(showMessageFile(QString)));
QDir dir(QDir::currentPath());
// 设置文件过滤器
dir.setNameFilters(QStringList("*.h"));
ui->listWidget->addItem(dir.absolutePath() + "all '.h' files:");
ui->listWidget->addItems(dir.entryList());
// 创建目录并且cd过去
dir.mkdir("newdir");
dir.cd("newdir");
// 显示当前监视目录
ui->listWidget->addItem("now watching dir is : " + dir.absolutePath());
// 为 watcher 设置需要监视的目录
m_fileSysWatcher.addPath(dir.absolutePath());
// 为 watcher 设置需要监视的文件
QFile file(dir.absolutePath() + "/test.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QFileInfo info(file);
m_fileSysWatcher.addPath(info.absoluteFilePath());
ui->listWidget->addItem("now watching file is : " + info.absoluteFilePath());
file.close();
}
Widget::~Widget()
{
delete ui;
}
void Widget::showMessageDir(const QString &path)
{
ui->listWidget->addItem("dir changed: " + path);
}
void Widget::showMessageFile(const QString &path)
{
ui->listWidget->addItem("file changed: " + path);
}
当 newdir 下文件改变内容或者文件数目等发生改变的时候,就会触发 directoryChanged 信号,文件内容改变自会触发 fileChanged 信号!
参考:
不二如是:https://fishc.com.cn/forum.php?mod=viewthread&tid=78193&ctid=447