Search code examples
qthttpqnetworkaccessmanager

Qt QNetworkAccessManager & multiple QNetworkReplay


I have two http get methods.

First is getting UserID and second is getting full information about current user;

I want to handle finished signlas with different slots

handle GetUserID finished with GetUserIDCompleted and handle GetUserDetails with GetUserDetailsCompleted

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    nam = new QNetworkAccessManager(this);

    GetUserID();
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(GetUserIDCompleted(QNetworkReply*)));

    GetUserDetails();
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(GetUserDetailsCompleted(QNetworkReply*)));
}

does it possible to get QNetworkReplay in different SLOTS?

enter image description here


Solution

  • maybe you can do something like this: having an enum of the different methods

    enum GetMethod
    {
        getUserId,
        getUserDetails
    };
    

    And you keep a hash of the reply and the corresponding method:

    QHash<QNetworkReply*, GetMethod> hash;
    
    QNetworkReply *reply1 = nam->post(requestUserId, data);
    hash[reply1] = GetMethod::getUserId;
    
    QNetworkReply *reply2 = nam->post(requestUserDetails, data);
    hash[reply2] = GetMethod::getUserDetails;
    
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*)));
    

    And have one slot that calls the right function

    void MainWindow::finished(QNetworkReply *reply)
    {
        switch(hash[reply])
        {
        case GetMethod::getUserId:
            GetUserIDCompleted(reply);
            break;
        case GetMethod::getUserDetails:
            GetUserDetailsCompleted(reply);
            break;
        }
    
        hash.remove(reply);
    }
    

    I haven't tried it and took some shortcuts but you get the spirit of it =) . It seems that you can retrieve the request with the answer, but I think it is easier with the enum.

    Hope it helped