我正在尝试使用以下代码下载网页的源代码 头文件:
#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。我错过了什么?
答案 0 :(得分:4)
void MainWindow::on_download_clicked()
{
CDownloader cDown;
cDown.Do_Download();
}
当该方法返回时,cDown
会立即被破坏。只要您没有收到并处理回复,您就需要保持该对象的存活。
为此,cDown
应该是MainWindow
的成员,或者指向({或指针集合)CDownloader
的指针应保留(并妥善处理)某处你的代码。