Make a request to the web service, get a json response and update the GUI in Qt

Trying to learn Web Services using Qt (using Qt Creator 4.1.0) and connecting data to a graphical interface . I read a few online examples (primarily: 1 , 2, and 3 ), but my low level of coding and the fact that I could not find complete examples demonstrating my needs brought me here.)

I created a simple example that contains all my flaws:

  • Request an HTTP request for an existing web service every 30 seconds.
  • The web service then responds to sending the json data object (see below for this json example format), which we receive and parse .
  • Then Qt will display all parsed json data on a simple graphical interface (see below what this graphical interface looks like.

Json data format - example:

{
    "city": "London",
    "time": "16:42",
    "unit_data": 
        [
            {
                "unit_data_id": "ABC123",
                "unit_data_number": "21"
            }
        ]
}

My simple Qt GUI (made in Qt Creator) displaying all received parsed data: my simple Qt GUI design

I would really appreciate any example of complete code that shows how we can make a request to a web service, and then how to get a json response. Finally, how to plug in a GUI in Qt to display this data as soon as it is received.

I'm just starting to explore this area, and I need a simple example of complete code to make me move.

+2
1

, GET -, QNetworkAccessManager JSON QJsonDocument.

http://uinames.com/, JSON :

{
    "name":"John",
    "surname":"Doe",
    "gender":"male",
    "region":"United States"
}

JSON .

Screenshot example

#include <QtWidgets>
#include <QtNetwork>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //setup GUI (you could be doing this in the designer)
    QWidget widget;
    QFormLayout layout(&widget);
    QLineEdit lineEditName;
    QLineEdit lineEditGender;
    QLineEdit lineEditRegion;
    auto edits = {&lineEditName, &lineEditGender, &lineEditRegion};
    for(auto edit : edits) edit->setReadOnly(true);
    layout.addRow("Name:", &lineEditName);
    layout.addRow("Gender:", &lineEditGender);
    layout.addRow("Region:", &lineEditRegion);
    QPushButton button("Get Name");
    layout.addRow(&button);

    //send request to uinames API
    QNetworkAccessManager networkManager;
    QObject::connect(&networkManager, &QNetworkAccessManager::finished,
                     [&](QNetworkReply* reply){
        //this lambda is called when the reply is received
        //it can be a slot in your GUI window class
        //check for errors
        if(reply->error() != QNetworkReply::NoError){
            for(auto edit : edits) edit->setText("Error");
            networkManager.clearAccessCache();
        } else {
            //parse the reply JSON and display result in the UI
            QJsonObject jsonObject= QJsonDocument::fromJson(reply->readAll()).object();
            QString fullName= jsonObject["name"].toString();
            fullName.append(" ");
            fullName.append(jsonObject["surname"].toString());
            lineEditName.setText(fullName);
            lineEditGender.setText(jsonObject["gender"].toString());
            lineEditRegion.setText(jsonObject["region"].toString());
        }
        button.setEnabled(true);
        reply->deleteLater();
    });
    //url parameters
    QUrlQuery query;
    query.addQueryItem("amount", "1");
    query.addQueryItem("region", "United States");
    QUrl url("http://uinames.com/api/");
    url.setQuery(query);
    QNetworkRequest networkRequest(url);
    //send GET request when the button is clicked
    QObject::connect(&button, &QPushButton::clicked, [&](){
        networkManager.get(networkRequest);
        button.setEnabled(false);
        for(auto edit : edits) edit->setText("Loading. . .");
    });

    widget.show();
    return a.exec();
}

Edit:

, QTimer , connect button clicked - :

QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&](){
    networkManager.get(networkRequest);
    button.setEnabled(false);
    for(auto edit : edits) edit->setText("Loading. . .");
});
timer.start(60000); //60000 msecs = 60 secs

, , , networkManager, networkRequest, GUI timer , . , .

+3

Source: https://habr.com/ru/post/1690065/


All Articles