将值传递给slot并使用QNetWorkAccessManager获取其调用函数的反馈

时间:2017-07-02 10:45:08

标签: qt qt-signals qtnetwork

我想使用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

请不要介意我的英语。 请帮助我,谢谢!

1 个答案:

答案 0 :(得分:2)

这是一个完整的工作示例。我有这个窗口:

enter image description here

<强> 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 ......”