How to combine own message loop and Qt event loop?

帅比萌擦擦* 提交于 2019-12-11 10:18:45

问题


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.



来源:https://stackoverflow.com/questions/13054053/how-to-combine-own-message-loop-and-qt-event-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!