Time for action – writing the OOP conform code using QSignalMapper
A more elegant way that does not rely on sender()
would be to use QSignalMapper
and a local hash, in which all replies that are connected to that slot are stored. So, whenever you call QNetworkAccessManager::get()
, store the returned pointer in a member variable of the QHash<int, QNetworkReply*>
type and set up the mapper. Let's assume that we have the following member variables and that they are set up properly:
QNetworkAccessManager *m_nam; QSignalMapper *m_mapper; QHash<int, QNetworkReply*> m_replies;
Then, you connect the finished()
signal of a reply this way:
QNetworkReply *reply = m_nam->get(QNetworkRequest(QUrl(/*...*/))); connect(reply, SIGNAL(finished()), m_mapper, SLOT(map())); int id = /* unique id, not already used in m_replies*/; m_replies.insert(id, reply); m_mapper->setMapping(reply, id);
What just happened?
First, we posted the request and fetched the pointer to QNetworkReply
with reply. Then...