0

I have an application that does a presumably long operation on disk, that I want to start in the background as soon as the application opens. However, if the task is not done by the time the last window is closed, I need to cancel this operation.

Class doing long work in setRootPath:

class Scanner : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString currentPath READ currentPath NOTIFY currentPathChanged)
    Q_PROPERTY(bool done READ done NOTIFY doneChanged)
public:
    Scanner(QObject * parent = 0);
    QString currentPath() const;
    bool done() const;
    void setRootPath(QString root);
signals:
    void currentPathChanged(QString newPath);
    void doneChanged(bool newDone);
private:
    QString m_path;
    bool m_done;
};

Main:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    Scanner scanner{};

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("scanner", &scanner);
    QFuture<void> f = QtConcurrent::run(&scanner, &Scanner::setRootPath, QString("path/to/Pictures"));
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    f.waitForFinished(); // of course, this hangs the gui... how do I get around that?
    return app.exec();
}

I have read on the Qt forums that I need to connect to lastWindowChanged signal, but I can't figure out how to use QObject::connect here... what's my recipient?

Melodie
  • 305
  • 2
  • 8
  • read https://doc.qt.io/qt-5.9/qtconcurrent.html#run: *Note that the QFuture returned by QtConcurrent::run() does **not support canceling, pausing, or progress reporting**. The QFuture returned can only be used to query for the running/finished status and the return value of the function.* Use `QObject::connect(&app, &QGuiApplication::lastWindowClosed, &f, &QFuture::waitForFinished);` – eyllanesc Feb 19 '19 at 20:47
  • Thank you for your reply, however I'm afraid the compiler says "no matching function for call to QObject:: ..." – Melodie Feb 20 '19 at 18:21

0 Answers0