[SOLVED] Qt C++ QNetworkRequest not making any requests


I’m trying to fetch some data from an API using QNetworkRequest following this video (https://youtu.be/G06jT3X3H9E)

I have a RoR server running on localhost:3000 and I’m trying to fetch something from it.

.h file:

#ifndef WORKER_H
#define WORKER_H

#include <QObject>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QAuthenticator>
#include <QNetworkProxy>

class Worker : public QObject
    explicit Worker(QObject *parent = nullptr);


public slots:

    void get(QString code);

private slots:
    void readyRead();
    void authenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator);
    void encrypted(QNetworkReply *reply);
    void finished(QNetworkReply *reply);
    void networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accessible);
    void preSharedKeyAuthenticationRequired(QNetworkReply *reply, QSslPreSharedKeyAuthenticator *authenticator);
    void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator);
    void sslErrors(QNetworkReply *reply, const QList<QSslError> &errors);

    QNetworkAccessManager manager;

#endif // WORKER_H

.cpp file:

void Worker::get(QString code)
    qInfo() << "Getting something from the server...";
    QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(QString("http://localhost:3000/api/v1/circle_gift_cards/scan?codes=" + code))));
    connect(reply, &QNetworkReply::readyRead, this, &Worker::readyRead);

void Worker::readyRead()
    qInfo() << "ReadReady";
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
    if(reply) qInfo() << reply->readAll();

The result from:

Worker worker;

is: "Getting something from the server…"
it should print "ReadReady" when the request is ready, but I don’t think the request is being made, there’s nothing in the console either.

[Edit 1]
What is calling the worker is this

void MainWindow::on_lineEditScanCard_textChanged(QString code) {
    Worker worker(this->site);

It’s an Edit field(where the user is supposed to type a code

[Edit 2]

I removed all app code and did this:

#include <QApplication>
#include "Forms/mainwindow.h"
#include "Requests/worker.h"

int main(int argc, char *argv[]) {
  QApplication a(argc, argv);
  Worker worker;

  return a.exec();

And it worked… Why it does not work when called when the Edit text is changed?


Remember the concepts of scope, life cycle, and local variables? In your case worker is a local variable that will be destroyed instantly so the slot is not invoked, use

Worker * worker = new Worker; 
worker->get("abc"); //remember to delete the memory when you no longer use it

Answered By – Diego Oliveira

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *