我正在尝试使用以下代码下载网页的源代码
头文件:
#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。我想念什么?
最佳答案
void MainWindow::on_download_clicked()
{
CDownloader cDown;
cDown.Do_Download();
}
当该方法返回时,
cDown
立即被破坏。您至少要在没有收到并处理回复的情况下使该对象保持 Activity 状态。为此,
cDown
应该是MainWindow
的成员,或者应该在代码中的某个位置维护(并正确处理)指向CDownloader
的指针(或指向该指针的集合)。关于c++ - QNetworkAccessManager问题获取网页,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11273582/