Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.