Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4238587
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-08-01 15:51:07

工程代码:  MonitorFS.rar  

精通Qt4编程 chapter08

   在Qt中可以使用QFieleSystemWatcher 类来监视文件和目录的改变。使用  addPath函数来监视制定的文件和目录。如果需要监视多个目录,可以使用addPaths()来加入监视。要移除不许要监视的目录,可以使用 removePath() removePaths()函数

    当监视的文件被修改或删除时,产生一个fileChanged()信号。如果被监视的目录被改变或删除,产生 directoryChanged()信号

  1. #ifndef MSG_H
  2. #define MSG_H

  3. #include <QtCore>
  4. #include <QtGui>

  5. class Msg : public QWidget
  6. {
  7.     Q_OBJECT

  8. public:
  9.     Msg();

  10. public slots:
  11.     void directoryChanged(QString path);
  12.     void fileChanged(QString path);

  13. private:
  14.     QLabel* label;
  15.     QFileSystemWatcher fsWatcher;
  16. };
  17. #endif

  1. #include "Msg.h"

  2. 当监视的文件被修改或删除时,产生一个fileChanged()信号。如果被监视的目录被
  3. 改变或删除,产生 directoryChanged()信号。下列实现了监视指定目录的功能
  4. */
  5. Msg::Msg()
  6. {
  7.     QFont font;
  8.     font.setPointSize(24);
  9.     setFont(font);
  10.     QStringList args = qApp->arguments(); //获取目录
  11.     QString path;
  12.     if (args.count() > 1)
  13.         path = args[1];
  14.         else //假如没有参数,则当前目录作为参数
  15.         path = QDir::currentPath();

  16.     label = new QLabel();
  17.     label->setText(tr("监视的目录:") + path);
  18.     QVBoxLayout *layout = new QVBoxLayout;
  19.     layout->addWidget(label);
  20.     setLayout(layout);

  21.     fsWatcher.addPath(path);
  22.     connect(&fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChanged(QString)));
  23.     connect(&fsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
  24. }

  25. void Msg::directoryChanged(QString path)
  26. {
  27.     QMessageBox::information(NULL, tr("目录有变化"), path);
  28. }

  29. void Msg::fileChanged(QString path)
  30. {
  31.     QMessageBox::information(NULL, tr("文件有变化"), path);
  32. }









阅读(4254) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

sonichy2020-04-03 10:21:59

奇怪了:
QFileSystemWatcher FSW;  //无反应
QFileSystemWatcher *FSW = new QFileSystemWatcher;  //有效