Medical Imaging Interaction Toolkit  2025.08.99-f7084adb
Medical Imaging Interaction Toolkit
QmitkRun.h
Go to the documentation of this file.
1 /*============================================================================
2 
3 The Medical Imaging Interaction Toolkit (MITK)
4 
5 Copyright (c) German Cancer Research Center (DKFZ)
6 All rights reserved.
7 
8 Use of this source code is governed by a 3-clause BSD license that can be
9 found in the LICENSE file.
10 
11 ============================================================================*/
12 
13 #ifndef QmitkRun_h
14 #define QmitkRun_h
15 
16 #include <MitkQtWidgetsExports.h>
17 
18 #include <QEventLoop>
19 #include <QFutureWatcher>
20 #include <QProgressDialog>
21 #include <QString>
22 #include <QWidget>
23 
24 #include <QtConcurrent>
25 
26 #include <exception>
27 #include <functional>
28 
38 template<typename T>
39 T QmitkRunAsyncBlocking(const QString& title, const QString& label, std::function<T()> task)
40 {
41  QProgressDialog dialog(label, {}, 0, 0);
42  dialog.setWindowModality(Qt::ApplicationModal);
43  dialog.setWindowTitle(title);
44  dialog.setMinimumDuration(250);
45  dialog.show();
46 
47  T result{};
48  std::exception_ptr exception;
49 
50  auto future = QtConcurrent::run([&]() -> T {
51  try
52  {
53  return task();
54  }
55  catch (...)
56  {
57  exception = std::current_exception();
58  return T{};
59  }
60  });
61 
62  QFutureWatcher<T> watcher;
63  QEventLoop loop;
64 
65  QObject::connect(&watcher, &QFutureWatcher<T>::finished, [&]() {
66  result = watcher.result();
67  dialog.close();
68  loop.quit();
69  });
70 
71  watcher.setFuture(future);
72  loop.exec();
73 
74  if (exception)
75  std::rethrow_exception(exception);
76 
77  return result;
78 }
79 
80 MITKQTWIDGETS_EXPORT void QmitkRunAsyncBlocking(const QString& title, const QString& label, std::function<void()> task);
81 
82 #endif
MITKQTWIDGETS_EXPORT
#define MITKQTWIDGETS_EXPORT
Definition: MitkQtWidgetsExports.h:15
QmitkRunAsyncBlocking
T QmitkRunAsyncBlocking(const QString &title, const QString &label, std::function< T()> task)
Runs a long task in a background thread while keeping the UI responsive.
Definition: QmitkRun.h:39
MitkQtWidgetsExports.h