Qt工作笔记-使用QFileSystemWatcher监控文件是否改变

程序运行截图如下:
这里写图片描述

代码如下:
widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
class QFileSystemWatcher;

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
    void loadFile(const QString &path);

public slots:
    void onFileChanged(const QString &path);

private:
    QFileSystemWatcher *m_fileWatcher;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.cpp

#include "widget.h"
#include <QFileSystemWatcher>
#include <QFile>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    m_fileWatcher=new QFileSystemWatcher;
    connect(m_fileWatcher,&QFileSystemWatcher::fileChanged,this,&Widget::onFileChanged);

    loadFile("demo.txt");
}

Widget::~Widget()
{

}

void Widget::loadFile(const QString &path)
{
    if(path.isEmpty()||!QFile::exists(path)){
        return;
    }
    m_fileWatcher->addPath(path);
}

void Widget::onFileChanged(const QString &path)
{
    QFile file(path);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text)){
        qDebug()<<file.readAll();
    }
}

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/81068737