Running code in the main loop

前端 未结 3 1800
予麋鹿
予麋鹿 2020-12-20 18:19

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

3条回答
  •  我在风中等你
    2020-12-20 19:02

    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();
        }
      }
    );
    

提交回复
热议问题