简体   繁体   中英

Qt4 QNetworkManager Hangs

I'm trying to write an application using QNetworkManager. I have simplified the code down to the problem. The following code hangs, and I have no idea why:

main.cpp:

#include <QApplication>
#include "post.h"

int main(int argc, char *argv[]) {
   QApplication app(argc, argv);
   post("http://google.com/search", "q=test");
   return app.exec();
}

post.h:

#ifndef _H_POST
#define _H_POST

#include <QNetworkAccessManager>
#include <QNetworkRequest>

class post : public QObject {
   Q_OBJECT

   public:
      post(QString URL, QString data);

   public slots:
      void postFinished(QNetworkReply* reply);

   protected:
      QNetworkAccessManager *connection;

};

#endif

post.cpp:

#include <QApplication>
#include <QUrl>
#include "post.h"

post::post(QString URL, QString data) {
   connection = new QNetworkAccessManager(this);
   connect(connection, SIGNAL(finished(QNetworkReply*)), this, SLOT(postFinished(QNetworkReply*)));
   connection->post(QNetworkRequest(QUrl(URL)), data.toAscii());
}

void post::postFinished(QNetworkReply*) {
   qApp->exit(0);
}

Some Googling shows it may be because I have everything on one thread, but I have no idea how to change that in Qt... none of the network examples show this.

I just tried it with the same results. The problem is that you are creating the post object by only calling the constructor. Since you are not specifying an object it is getting destroyed right away (to check this create a destructor and see when it gets called.)

try:

post p("http://google.com/search","q=test");

Then your slot gets called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM