#include "MainThread.h" #include #include std::shared_ptr MainThread::createShared(QObject* bindObject) { return std::shared_ptr(new MainThread(bindObject), [=](QObject* mainThread) { mainThread->deleteLater(); }); } MainThread::MainThread(QObject* bindObject) : mBindObject(bindObject) , mIgnoreNullObject(bindObject == nullptr) { qRegisterMetaType>("std::function"); auto mainUIThread = qApp->thread(); if (this->thread() != mainUIThread) { this->moveToThread(mainUIThread); } } MainThread::~MainThread() { } void MainThread::post(std::function func) { QMetaObject::invokeMethod(createShared().get(), "mainThreadSlot", Q_ARG(std::function, func)); } void MainThread::mainThreadSlot(std::function func) { if ((mIgnoreNullObject || mBindObject) && func) { func(); } }