1

I create a QEventLoop object and trying to put quit() message before starting it so my intention is to enter and quit a loop:

QEventLoop loop;
loop.connect(this, SIGNAL(sig()), SLOT(quit()));
emit sig();
loop.exec(); // can't get past this point

But thread is cycling in loop and never quits ...
How can I achieve intended behaviour ?

Alexey Andronov
  • 582
  • 6
  • 28
  • What is the purpose of this? – thuga Mar 02 '16 at 12:11
  • @thuga I want to call `post()` and `get()` of `QNetworkAccessManager` from different threads. But these methods are need to be called from the owning thread. So I create `wrapperClass` which contains `QNetworkAccessManager`. And when user calls `wrapper.sendPostRequest(...)` my thread should wait for `QNetworkAccessManager` to execute the call and after that I can continue. Loops seemed like a reasonable way to pause thread and wait for 'wake up' signal ... :) – Alexey Andronov Mar 02 '16 at 14:02

1 Answers1

3

This in isolation doesn't appear to make much sense, but to provide an answer to your very question, you can connect with Qt::QueuedConnection and then the quit call will be received when running the event loop and then the loop will quit correctly.

This works because slots are executed in order of the connect calls, so another slot that too happens to be connected to sig() can do whatever it wants, even start an own event loop. However, the last connection is yours, and its queued call to quit will happen last with no other event loop action in between the queued call to quit and the call to loop.exec.

Remember that local QEventLoops, just like calls to QApplication::processEvents, are very dangerous. If you can change the code, try to setup a statemachine to do asynchronous work.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • thanks for the answer. I will test your suggestions little later and mark the answer if it work. I added explanation why I chose `QEventLoop` in the comment to the question, what do you think ? %) – Alexey Andronov Mar 02 '16 at 14:05