在Qt中,如果QtConcurrentRun在应用程序退出时尚未完成,该如何取消?

时间:2019-02-19 20:35:03

标签: qt qobject qtconcurrent

我有一个应用程序可能在磁盘上执行了很长的操作,我想在应用程序打开后立即在后台启动。但是,如果在关闭最后一个窗口时仍未完成任务,则需要取消此操作。

类在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;
};

主要:

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();
}

我已经读过on the Qt forums,我需要连接到lastWindowChanged信号,但是我不知道如何在这里使用QObject :: connect ...我的接收者是什么?

0 个答案:

没有答案