5

Im new in Qt and im trying to understand the following signal-slot connection:

m_networkManager = new QNetworkAccessManager(this);
QNetworkReply *reply = m_networkManager->get(request);
connect(reply, SIGNAL(finished()),this, SLOT(onRequestCompleted()));

Why we connect the "finished" signal after the get-request?...What happened, if the network connection in line-2 was faster executed before the slot connection (line-3) was made?

I know, that this code will work. but i want to understand how this is possible :)

Daggit
  • 53
  • 3

1 Answers1

6

It's not possible for the finished() signal to emit because you haven't yielded to the event loop yet. Even if somehow the get request got sent and then came back, your code is still executing and will continue to execute until you've yielded to the event loop. Only then will the reply object ever get a chance to actually do anything, such as parsing the get response and emitting the corresponding signal.

Chris
  • 17,119
  • 5
  • 57
  • 60
  • To add, there are situations in which the request could actually complete immediately (think f.i. when accessing `file` or `qrc` URL schemes; there's no network involved). In any case, QNR will not fire `finished()` before returning to the event loop. The standard way to implement that in Qt -- as a general pattern, useful for your classes -- is calling `QMetaObject::invokeMethod(this, "signalName", Qt::QueuedConnection)`. – peppe May 18 '13 at 21:49
  • 1
    I personally have a case where the thread executing the second and third lines of code in the original post is not the main thread (the main thread is the thread that is processing the events). Because they are separate threads, does that make it possible for the events to be processed before connect() is called? The QNetworkAccessManager was created in the main thread, but the get() occurs in a separate thread. – Patrick Avery Nov 30 '17 at 18:04