Reputation: 2008
I want to send a post request to a server and I do something like this:
function makePost(){
QNetworkAccessManager *networkManager = new QNetworkAccessManager();
qDebug()<<"1";
bool ret = connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(serviceRequestFinished(QNetworkReply*)));
qDebug()<<"2: " <<ret;
QUrl serviceUrl = QUrl("http://someurl/json");
QNetworkRequest request(serviceUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QString content = "";
networkManager->post(request, content.toUtf8());
}
But the slot serviceRequestFinished()
is not called at all! I must mention that I used Wireshark to track the request/response and I found that the request(post) is being sent and the server returns a response back with status 200
(ok). Also the ret
variable returns true
, i.e. the connection between signal and slot was made successfully. Any of you have any idea why this doesn't work? Thank you!:)
EDIT
The code that cause the problem - see my answer - is this:
{
MyObjectWithSlot obj;
obj.makePost();
}
Upvotes: 3
Views: 2120
Reputation: 5095
You need to tell Qt to connect the signal finished()
, which is called when post()
finishes, to a slot of your choice. Something like the following:
QObject::connect(networkManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
For more information about signals and slots, see this page.
Upvotes: 0
Reputation: 2008
Ok so I found my mistake! You can downvote as much as you want my answer or question but I would like to answer if someone else has a similar problem!
Be careful! The object that has the slot should be in scope and not terminate(destroyed) before the slot is called. As you can see in the edited part of my question, the object is created, it calls a function and then it's out of scope!
{
MyObjectWithSlot obj;
return obj.makePost();
}
Upvotes: 5