Search code examples
c++qtqnetworkaccessmanager

QNetworkAccessManager issue getting web page


I am trying to download the source code of a web page with the following code in header file:

#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

and the source file:

#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";
}

and on push button code:

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

but qDebug is never called in the result slot. What am i missing?


Solution

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

    When that method returns, cDown is immediately destructed. You need to keep that object alive at least as long as you haven't received and processed the reply.

    For that, either cDown should be a member of your MainWindow, or a pointer to (or collection of pointers to) CDownloader should be maintained (and properly disposed) somewhere in your code.