title: Execute slots inside a QThreadPool
body: <p>I have a class that should run in a thread and needs an event loop for the slots, currently I run it nicely with <code>moveToThread()</code>, but I'd like to use <code>QThreadPool</code> and I have encountered a problem.</p>
  
  <p>When run with <code>QThreadPool</code> the <code>run()</code> method of my runnable is called from a pooled thread (I check this with <code>QThread::currentThread()</code>), but my slots aren't running in the pooled thread, so I think the object isn't moved to a thread in the pool.</p>
  
  <p>I think this because I know the slots are run in the receiver's thread, which is exactly the (correct) behaviour I get when using the <code>moveToThread()</code> method and a <code>QThread</code>.</p>
  
  <p>How do I get my <code>QRunnable</code> (Foo in the example below) to be run entirely in the pooled threads?
  Or is it something I'm doing wrong or understood wrong?</p>
  
  <p>The following POC demonstrates the problem:</p>
  
  <p><strong>foo.h</strong></p>
  
  <pre><code>#ifndef FOO_H
  #define FOO_H
  
  #include &lt;QObject&gt;
  #include &lt;QRunnable&gt;
  #include &lt;QEventLoop&gt;
  
  class Foo : public QObject, public QRunnable
  {
      Q_OBJECT
  public:
      explicit Foo(int data, QObject *parent = 0);
      void run();
  signals:
      void startWorking();
  public slots:
      void doWork();
  
  private:
      QEventLoop eventLoop;
      int data;
  };
  
  #endif // FOO_H
  </code></pre>
  
  <p><strong>foo.cpp</strong></p>
  
  <pre><code>#include "foo.h"
  
  #include &lt;QThread&gt;
  #include &lt;QDebug&gt;
  
  Foo::Foo(int d, QObject *parent) :
      QObject(parent), eventLoop(this), data(d)
  {
  }
  
  void Foo::run()
  {
      qDebug() &lt;&lt; "run() in: " &lt;&lt; QThread::currentThread();
      connect(this, SIGNAL(startWorking()), this, SLOT(doWork()));
      emit startWorking();
      eventLoop.exec();
  }
  
  void Foo::doWork()
  {
      qDebug() &lt;&lt; "doWork() in: " &lt;&lt; QThread::currentThread();
  }
  </code></pre>
  
  <p><strong>main.cpp</strong></p>
  
  <pre><code>#include &lt;QCoreApplication&gt;
  #include &lt;QThreadPool&gt;
  
  #include "foo.h"
  
  int main(int argc, char *argv[])
  {
      QCoreApplication a(argc, argv);
  
      Foo *foo = new Foo(42);
  
      QThreadPool::globalInstance()-&gt;start(foo);
  
      return a.exec();
  }
  </code></pre>
  
  <p>Please note, however, that in my real code the signal won't be emitted right away, because it will be after I receive some data on the network.</p>
  
  <p>PS: The POC can also be found <a href="https://gist.github.com/paullik/6086849" rel="nofollow">here</a>.</p>