30Jul/1119
Why QNetworkAccessManager should not have the finished(QNetworkReply *) signal
I was recently writing some network code in Qt using QNetworkAccessManager and again I did the mistake I've already done a few times. The reason for my mistake was that QNetworkAccessManager provides the finished(QNetworkReply *) signal. There are essentially two ways to request some data from the net using QNetworkAccessManager. In the first approach you have the QNetworkAccessManager as an instance variable in your class and you connect the finished(QNetworkReply *) signal from the instance variable to your slot. This is a tempting solution as it provides a quick and easy solution to fetch some data from the net. void MyApp::getData() { QNetworkRequest request; request.setUrl(QUrl("http://www.domain.foo")); m_networkManager = new QNetworkAccessManager(this); // Instance variable connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onRequestCompleted(QNetworkReply *))); m_networkManager->get(request); } void MyApp::onRequestCompleted(QNetworkReply *reply) { QByteArray data = reply->readAll(); } The second approach, which does exactly the same thing, is to connect the finished() signal from the QNetworkReply instance, which QNetworkAccessManager returns upon a call to get() or post() methods, to your slot. Note how you can also in this case get the QNetworkReply object that contains the completed request's data using the QObject::sender() method despite the fact that you don't get the result as a signal parameter. void MyApp::getData() { QNetworkRequest request; request.setUrl(QUrl("http://www.domain.foo")); m_networkManager = new QNetworkAccessManager(this); QNetworkReply *reply = m_networkManager->get(request); connect(reply, SIGNAL(finished()), this, SLOT(onRequestCompleted())); } void MyApp::onRequestCompleted() { QNetworkReply *reply = qobject_cast-
Mardy
-
Johan Paul
-
-
Anonymous
-
Johan Paul
-
-
Toni Jovanoski
-
Johan Paul
-
Toni Jovanoski
-
-
-
Denis Kormalev
-
Johan Paul
-
-
Mason Chang
-
Toni Jovanoski
-
Dan
-
-
Johan Paul
-
-
Andrea Martelli
-
Jarrod
-
Johan Paul
-
DrTebi
-
shackra sislock
-
-
-
WU Long