diff --git a/src/asyncexec.hpp b/src/asyncexec.hpp index ba36b2682..7899676c7 100644 --- a/src/asyncexec.hpp +++ b/src/asyncexec.hpp @@ -25,3 +25,30 @@ public: private: std::function action; }; + +// Taken from +// https://stackoverflow.com/questions/21646467/how-to-execute-a-functor-or-a-lambda-in-a-given-thread-in-qt-gcd-style +// Qt 5/4 - preferred, has least allocations +template +static void postToThread(F &&fun, QObject *obj = qApp) +{ + struct Event : public QEvent { + using Fun = typename std::decay::type; + Fun fun; + Event(Fun &&fun) + : QEvent(QEvent::None) + , fun(std::move(fun)) + { + } + Event(const Fun &fun) + : QEvent(QEvent::None) + , fun(fun) + { + } + ~Event() + { + fun(); + } + }; + QCoreApplication::postEvent(obj, new Event(std::forward(fun))); +}