I need a way to run an update function of my own in the main thread. I couldn\'t find a signal that would tick me every time the main loop runs.
Am I doing this wr
Yet another way would be to override:
bool QCoreApplication::event(QEvent *e)
register a user QEvent and post the event to QCoreApplicatio::instance(). Obviously, the QTimer approach is superior, but this one will work even if the issuing thread was not created by Qt (QThread).
example:
class MainThreadEvent: public QEvent
{
std::function f_;
public:
template
explicit MainThreadEvent(F&& f) :
QEvent(event_type()),
f_(std::forward(f))
{
}
void invoke()
{
f_();
}
static auto event_type()
{
static int et{-1};
return QEvent::Type(-1 == et ? et = registerEventType() : et);
}
template
static void post(F&& f)
{
auto const app(QCoreApplication::instance());
app->postEvent(app, new MainThreadEvent(std::forward(f)));
}
};
class UserApplication: public QApplication
{
using QApplication::QApplication;
bool event(QEvent* const e) final
{
if (MainThreadEvent::event_type() == e->type())
{
return static_cast(e)->invoke(), true;
}
else
{
return QApplication::event(e);
}
}
};
EDIT: example for an update() from an arbitrary thread:
MainThreadEvent::post(
[p = QPointer(this)]()
{
if (p)
{
p->update();
}
}
);