How to combine own message loop and Qt event loop?

2019-07-28 23:30发布

问题:

I have a class derived from QThread: class MyClass : public QThread. In the run method I have "my own" message loop:

run() { 
  // exec(); // while not reached    
  while (_runMessageLoop && ...) {
    hr = CallDispatch(.....);
    if (hr== 0) QThread::msleep(100); 
    // QCoreApplication::processEvents(); // Does not work
  }
}

Since exec() is not executed, I have no Qt event loop. This obviously causes signal / slots not to work correctly. Is there any chance to combine the Qt and my own message loop? Or do I need a frequently firing timer in order to do what I have accomplished in my infinite loop?

回答1:

The right way "Qt-wise" is to use a timer and let Qt manage the event loop.

If you need to depend on external things, you can use things like QAbstractSocket to send events when data comes in over an external socket, eg.



回答2:

This is not really the answer for implementing the event loop correctly, I'm fairly sure there is a way, but more of a workaround:

Start the thread normally, exec() and all, and connect the start signal to a slot (make sure it gets called in the right thread), then put your loop there, and call Qt's processEvents() in that loop. That makes sure Qt event loop gets properly set up.