获取网页的QNetworkAccessManager问题

时间:2012-06-30 11:08:00

标签: c++ qt qnetworkaccessmanager

我正在尝试使用以下代码下载网页的源代码 头文件:

#include <QObject>
#include <QHttp>
#include <QtNetwork>
#include <QFile>
#include <QDebug>

class CDownloader : public QObject
{
  Q_OBJECT
public:
  explicit CDownloader(QObject *parent = 0);

void Do_Download();

signals:

public slots:
  void result(QNetworkReply*);
private:   
  QNetworkAccessManager *manager;
  QNetworkReply *reply;
  QNetworkAccessManager qnam;
};

#endif // CDOWNLOADER_H

和源文件:

#include "cdownloader.h"

CDownloader::CDownloader(QObject *parent) :
QObject(parent)
{    
}

void CDownloader::Do_Download()
{
  manager = new QNetworkAccessManager(this);
  connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(result(QNetworkReply*)));
  manager->get(QNetworkRequest(QUrl("http://www.google.com")));
}

void CDownloader::result(QNetworkReply *reply)
{
     qDebug() << "loading complete";
}

并按下按钮代码:

void MainWindow::on_download_clicked()
{
  CDownloader cDown;
  cDown.Do_Download(); 
} 

但从未在结果槽中调用qDebug。我错过了什么?

1 个答案:

答案 0 :(得分:4)

void MainWindow::on_download_clicked()
{
  CDownloader cDown;
  cDown.Do_Download(); 
}

当该方法返回时,cDown会立即被破坏。只要您没有收到并处理回复,您就需要保持该对象的存活。

为此,cDown应该是MainWindow的成员,或者指向({或指针集合)CDownloader的指针应保留(并妥善处理)某处你的代码。