Skip to content

Instantly share code, notes, and snippets.

@iamazeem
Last active January 9, 2023 17:04
Show Gist options
  • Save iamazeem/0f690c039660f7b16ad43c2e7f31d71e to your computer and use it in GitHub Desktop.
Save iamazeem/0f690c039660f7b16ad43c2e7f31d71e to your computer and use it in GitHub Desktop.
Qt QFileSystemWatcher Example - Watch a directory and do some processing if it is changed with QEventLoop
// ----------------------------------------------
// List the contents of a directory if changed
// Using QFileSystemWatcher, QDirIterator and
// QEventLoop, and lambda function for connect
// ----------------------------------------------
#include <QObject>
#include <QEventLoop>
#include <QDebug>
#include <QFileSystemWatcher>
#include <QDirIterator>
void listDirectoryContents( const QString& dir ) noexcept
{
QFileSystemWatcher watcher;
watcher.addPath( dir );
QEventLoop loop;
QObject::connect( &watcher, &QFileSystemWatcher::directoryChanged,
[]( const QString& path )
{
QDirIterator it( path,
{ "*.txt" }, // Filter: *.txt
QDir::AllFiles ); // Files only
while ( it.hasNext() ) // List all txt files
{ // on console
qDebug() << it.next();
}
});
QObject::connect( &watcher, &QFileSystemWatcher::directoryChanged,
&loop, &QEventLoop::quit );
loop.exec();
}
// Example
int main()
{
const QString dir { "C:/Watchable" };
listDirectoryContents( dir );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment