title: How to execute a functor or a lambda in a given thread in Qt, GCD-style?
body: <p>In ObjC with GCD, there is a way of executing a lambda in any of the threads that spin an event loop. For example:</p>
  
  <pre><code>dispatch_sync(dispatch_get_main_queue(), ^{ /* do sth */ });
  </code></pre>
  
  <p>or:</p>
  
  <pre><code>dispatch_async(dispatch_get_main_queue(), ^{ /* do sth */ });
  </code></pre>
  
  <p>It executes something (equivalent to <code>[]{ /* do sth */ }</code> in C++) in the main thread's queue, either blocking or asynchronously.</p>
  
  <p>How can I do the same in Qt?</p>
  
  <p>From what I have read, I guess the solution would be somehow to send a signal to some object of the main thread. But what object? Just <code>QApplication::instance()</code>? (That is the only object living in the main thread at that point.) And what signal?</p>
  
  <hr>
  
  <p>From the current answers and my current research, it really seems that I need some dummy object to sit in the main thread with some slot which just waits to get in some code to execute.</p>
  
  <p>So, I decided to subclass <code>QApplication</code> to add that. My current code, which doesn't work (but maybe you can help):</p>
  
  <pre><code>#include &lt;QApplication&gt;
  #include &lt;QThread&gt;
  #include &lt;QMetaMethod&gt;
  #include &lt;functional&gt;
  #include &lt;assert.h&gt;
  
  class App : public QApplication
  {
      Q_OBJECT
  
  public:
      App();
  
  signals:
  
  public slots:
      void genericExec(std::function&lt;void(void)&gt; func) {
          func();
      }
  
  private:
      // cache this
      QMetaMethod genericExec_method;
  public:
      void invokeGenericExec(std::function&lt;void(void)&gt; func, Qt::ConnectionType connType) {
          if(!genericExec_method) {
              QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(std::function&lt;void(void)&gt;)");
              int methodIndex = this-&gt;metaObject()-&gt;indexOfSlot(normalizedSignature);
              assert(methodIndex &gt;= 0);
              genericExec_method = this-&gt;metaObject()-&gt;method(methodIndex);
          }
          genericExec_method.invoke(this, connType, Q_ARG(std::function&lt;void(void)&gt;, func));
      }
  
  };
  
  static inline
  void execInMainThread_sync(std::function&lt;void(void)&gt; func) {
      if(qApp-&gt;thread() == QThread::currentThread())
          func();
      else {
          ((App*) qApp)-&gt;invokeGenericExec(func, Qt::BlockingQueuedConnection);
      }
  }
  
  static inline
  void execInMainThread_async(std::function&lt;void(void)&gt; func) {
      ((App*) qApp)-&gt;invokeGenericExec(func, Qt::QueuedConnection);
  }
  </code></pre>