How to combine own message loop and Qt event loop?

2019-07-28 22:53发布

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?

2条回答
乱世女痞
2楼-- · 2019-07-28 23:46

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.

查看更多
【Aperson】
3楼-- · 2019-07-28 23:48

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.

查看更多
登录 后发表回答