new way to impl main thread

This commit is contained in:
王劲鹏 2021-02-22 18:54:29 +08:00 committed by osborn
parent 2048320470
commit 66649fe0f0

View File

@ -15,18 +15,11 @@ public:
} }
template <typename Function> template <typename Function>
static void ensureRunInMain(Function &&function) { static void ensureRunInMain(Function &&function,
struct Event : public QEvent { QThread *thread = qApp->thread()) {
using DecayedFunction = typename std::decay<Function>::type; auto *obj = QAbstractEventDispatcher::instance(thread);
DecayedFunction decayedFunction; Q_ASSERT(obj);
Event(DecayedFunction &&decayedFunction) QMetaObject::invokeMethod(obj, std::forward<Function>(function));
: QEvent(QEvent::None), decayedFunction(std::move(decayedFunction)) {}
Event(const DecayedFunction &decayedFunction)
: QEvent(QEvent::None), decayedFunction(decayedFunction) {}
~Event() { decayedFunction(); }
};
QCoreApplication::postEvent(qApp,
new Event(std::forward<Function>(function)));
} }
}; };