1

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

#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 永远不会在结果槽中调用。我错过了什么?

4

1 回答 1

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

当该方法返回时,cDown立即销毁。至少只要您没有收到并处理回复,您就需要保持该对象处于活动状态。

为此,要么cDown应该是您的成员,要么应该在代码中的某处维护(并正确处理)MainWindow指向(或指向的指针集合)的指针。CDownloader

于 2012-06-30T12:07:05.950 回答