Paste

URL To paste - | raw - Sun Jun 03 2018 13:46:38 GMT+0000 (Coordinated Universal Time)
#include <QCoreApplication>
#include <QEventLoop>
#include <QTemporaryFile>
#include <QDebug>
#include <QTimer>
#include <QTime>
#include <chrono>
#include <iostream>
#include <future>

using namespace std::chrono_literals;

int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);

  int count = 0; // This should be the number of files that have to be deleted.

  // A timer to send a delete update every 300ms.
  QTimer demo;
  demo.setInterval(300ms);

  // You should connect this to DeleteJobPrivate::slotReport, but take special care in updating the class variables:
  // - m_processedFiles
  // - m_totalFilesDirs
  // Otherwise the progress will be wrong.
  QObject::connect(&demo, &QTimer::timeout, [&count]()
  {
    qDebug() << QTime::currentTime() << QString(" No. of files deleted: %1").arg(count);
  });
  demo.start();

  // We need a temporary eventloop to keep the calling application alive while removing files.
  QEventLoop loop;

  // Note: Do pass in a list of files to delete as one of the lambda captures.
  // Also pass in:
  // - m_processedFiles
  // - m_totalFilesDirs
  // and update accordingly.
  auto deleteResult = std::async(std::launch::async, [&loop, &count]()
  {
    // Everything in this scope runs off-main-thread. Make it as expensive as you want.
    // Iterate over the files/folders...
    while (count < 100)
    {
      // ... and delete them here.
      std::this_thread::sleep_for(50ms);
      count++;
    }

    // Quit the eventloop instance, this unblocks the function that called exec on that loop object.
    loop.quit();

    // Return whatever the result was. Should be checked in the parent function.
    return true;
  });

  // This blocks the function at _this_ point till quit() is called on the loop.
  loop.exec();

  // We get here if quit() was called. Get the value from the std::async return (the bool of the delete call)
  // And do whatever checks you want.
  if (deleteResult.get())
  {
    qDebug() << "All files have been removed!";
  }
  else
  {
    qDebug() << "Delete failed? Permission denied?";
  }

  demo.stop();

  return a.exec();
}