Qt: connect a signal after a request is sent in QN

2019-05-18 11:13发布

This question already has an answer here:

I was checking some simple examples of using QNetworkAccessManager and I found this (Assuming that manager is a QNetworkAccessManager:

QNetworkRequest request;
request.setUrl(QUrl("http://www.someserver.com"));

QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
    this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
    this, SLOT(slotSslErrors(QList<QSslError>)));

As far as I understand, the call to manager->get will send out a GET request. The slots to handle the answer to that request, however, are connected only after the call is sent, which does not seems to make sense for me. Here my question:

  • isn't it a problem to connect the slots to the signals after the request is done? Can it happen that the request is done and the signals are emitted before the connection takes place, and hence, that the signals are missed and never processed by the corresponding slots?

Thanks!

L.

UPDATE: As pointed out by cyber_raj, this question has been already answered here: Qt signal slot connection - QNetworkAccessManager

1条回答
Deceive 欺骗
2楼-- · 2019-05-18 11:34

Not a problem. The get call is asynchronous: http://doc.qt.io/qt-5/qnetworkaccessmanager.html#details

QNetworkAccessManager queues the requests it receives, and runs 6 asynchronous tasks per time. So there's no much room to an error as you point.

But if you're afraid you can try the first example, connecting the signals of the manager:

QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
        this, SLOT(replyFinished(QNetworkReply*)));

manager->get(QNetworkRequest(QUrl("http://qt-project.org")));
查看更多
登录 后发表回答