我想使用QNetWorkAccessManager
完成HTTP-GET
并尝试将值传递到reply_finished
广告位,然后我希望从广告位获得反馈到其调用函数(例如{{ 1}})。我使用了here
并将一个点作为值传递给MainWindow
槽,但我的应用程序崩溃了。
以下是我的reply_finished
代码:
MainWindow
QHash<QNetworkReply*, QString*> data_storage;
QString data="";
manager = new QNetworkAccessManager(this);
QNetworkReply* reply =manager->get(QNetworkRequest(QUrl("http://example.com")));
data_storage[reply] = &data;
connect(manager, SIGNAL(finished(QNetworkReply*)),this,SLOT(reply_Finished(QNetworkReply*)));
广告位代码:
reply_finshed
请不要介意我的英语。 请帮助我,谢谢!
答案 0 :(得分:2)
这是一个完整的工作示例。我有这个窗口:
<强> mainwindow.h 强>
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QString>
#include <QHash>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_btnSendRequest_clicked();
private:
Ui::MainWindow *ui;
QNetworkAccessManager _manager;
QHash< QNetworkReply*, QString* > _storage;
};
#endif // MAINWINDOW_H
<强> mainwindow.cpp 强>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkRequest>
#include <QUrl>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnSendRequest_clicked()
{
QNetworkRequest request { QUrl{ "http://www.stroustrup.com/" } };
QNetworkReply* reply = _manager.get( request );
QString* data = new QString{ "Test Data! " };
_storage[ reply ] = data;
connect( &_manager, &QNetworkAccessManager::finished,
[this]( QNetworkReply* reply )
{
if ( reply->error() )
{
qWarning() << "Error:" << reply->errorString();
return;
}
QString* data = _storage[ reply ];
if ( data )
{
const auto& appendedData = data->append( "Appended data!" );
qDebug() << "Data:" << appendedData;
qDebug() << "Response:" << reply->readAll();
_storage.remove( reply );
delete reply;
delete data;
}
});
}
我在lambda
信号slot
上使用了QNetworkAccessManager::finished
。希望你能搞清楚。
单击Send Request
按钮,输出将为:
数据:“测试数据!附加数据!”
回复:“...... www.stroustrup.com Homepage Source ......”