Watching for file system changes in Qt

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Nokia 5800 XPressMusic
Platform(s): S60 5th Edition
S60 5th Edition
Keywords: QFileSystemWatcher
Created: User:Kbwiki (30 Oct 2009)
Last edited: hamishwillee (30 May 2013)


This article provides a way for a Qt application to monitor the file system for changes to files and directories by watching a list of specified paths.


Multiple files and/or directories can be monitored by providing their paths to the QFileSystemWatcher instance and connecting the directoryChanged() and fileChanged() signals to slot functions that handle the events of modifying or removing a file and a directory, respectively.

Watching for changes in the file system

 // Constructing QFileSystemWatcher
QString pathToWatch;
m_watcher = new QFileSystemWatcher( this ); // pass this (QObject) as parent
// Watching for changes in the default location for pictures
pathToWatch.append( QDesktopServices::storageLocation( QDesktopServices::PicturesLocation ) );
m_watcher->addPath( pathToWatch );
//Adding another path, watching for changes in specified file
m_watcher->addPath( pathToWatch + "someImage.jpg" );
// Connect signals to our slots
connect( m_watcher, SIGNAL( directoryChanged ( const QString& ) ),
this, SLOT( trackChanged( const QString ) ) );
connect( m_watcher, SIGNAL( fileChanged ( const QString& ) ),
this, SLOT( trackChanged( const QString ) ) );

Slot implementation

In the following code, FileWatcher is our own class, derived from QObject. A change log is simply written to a file.

 void FileWatcher::trackChanged( const QString & entry )
log( path );

Logging the changes into a file

  #include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QDateTime>
  void MainWindow::log( const QString & entry )
QFile file("c:\\data\\LogFileSystemChanges.txt");
if ( !file.open( QIODevice::Append | QIODevice::Text ) )
QTextStream out( &file );
QFileInfo info( entry );
if( info.isDir() ) {
out << "Dir ";
} else {
out << "File ";
if( info.exists() ) {
out << "changed: ";
} else {
out << "removed: ";
QString format("dd.MM.yyyy/hh:mm:ss.zzz");
out << QDateTime::currentDateTime().toString(format) << ":\t" << entry << "\n";


The act of monitoring files and directories for modifications consumes system resources. This implies that there is a limit to the number of files and directories that your process can monitor simultaneously.

This page was last modified on 30 May 2013, at 09:34.
132 page views in the last 30 days.