简体   繁体   English

Qt4 QNetworkManager挂起

[英]Qt4 QNetworkManager Hangs

I'm trying to write an application using QNetworkManager. 我正在尝试使用QNetworkManager编写应用程序。 I have simplified the code down to the problem. 我已将代码简化为问题。 The following code hangs, and I have no idea why: 以下代码挂起,我不明白为什么:

main.cpp: 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: 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: 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. 一些谷歌搜索显示它可能是因为我在一个线程上拥有所有内容,但我不知道如何在Qt中更改它...没有一个网络示例显示这一点。

I just tried it with the same results. 我只是尝试了相同的结果。 The problem is that you are creating the post object by only calling the constructor. 问题是你只是通过调用构造函数来创建post对象。 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. 然后你的插槽被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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