2023-07-26 17:48:35 +08:00
|
|
|
#include "MainThread.h"
|
|
|
|
#include <QGuiApplication>
|
|
|
|
#include <QMetaMethod>
|
|
|
|
|
2023-09-13 15:11:22 +08:00
|
|
|
std::shared_ptr<MainThread> MainThread::createShared(QObject* bindObject){
|
2023-07-26 17:48:35 +08:00
|
|
|
return std::shared_ptr<MainThread>(new MainThread(bindObject), [=](QObject* mainThread) {
|
|
|
|
mainThread->deleteLater();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-09-13 15:11:22 +08:00
|
|
|
MainThread::MainThread(QObject* bindObject): _bindObject(bindObject), _ignoreNullObject(bindObject == nullptr){
|
2023-07-26 17:48:35 +08:00
|
|
|
qRegisterMetaType<std::function<void()>>("std::function<void()>");
|
|
|
|
auto mainUIThread = qApp->thread();
|
|
|
|
if (this->thread() != mainUIThread)
|
|
|
|
{
|
|
|
|
this->moveToThread(mainUIThread);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-13 15:11:22 +08:00
|
|
|
MainThread::~MainThread(){
|
2023-07-26 17:48:35 +08:00
|
|
|
}
|
|
|
|
|
2023-09-13 15:11:22 +08:00
|
|
|
void MainThread::post(std::function<void()> func){
|
2023-07-26 17:48:35 +08:00
|
|
|
QMetaObject::invokeMethod(createShared().get(), "mainThreadSlot", Q_ARG(std::function<void()>, func));
|
|
|
|
}
|
|
|
|
|
2023-09-13 15:11:22 +08:00
|
|
|
void MainThread::mainThreadSlot(std::function<void()> func){
|
|
|
|
if ((_ignoreNullObject || _bindObject) && func)
|
2023-07-26 17:48:35 +08:00
|
|
|
{
|
|
|
|
func();
|
|
|
|
}
|
|
|
|
}
|