Search code examples
c++qtqt-signals

Qt Signals and Slots not working inside of QObject


I'm trying to create a client class for my API on the server, but my slot doesn't work after the request. The connect function returns true, which should mean that signal and slot are connected to each other.

header file

#ifndef QRESTCLIENT_H
#define QRESTCLIENT_H


#include <QObject>
#include <QUrl>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

class QRestClient : public QObject
{
    Q_OBJECT
public:
    explicit QRestClient(QUrl root_url, QObject *parent = nullptr);
    bool ping();

private:
    QUrl root_url;

private slots:
    void ping_finished(QNetworkReply * response);

};

#endif // QRESTCLIENT_H

cpp file

#include "qrestclient.h"

QRestClient::QRestClient(QUrl root_url, QObject *parent)
    : QObject{parent}
{
    this->root_url = root_url;
}

void QRestClient::ping_finished(QNetworkReply * response) {
    qDebug() << "It is here 3";
    qDebug() << response->readAll();
};

bool QRestClient::ping()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    qDebug() << connect(manager, &QNetworkAccessManager::finished,
            this, &QRestClient::ping_finished);

    qDebug() << "It is here 1";
    manager->get(QNetworkRequest(this->root_url));
    qDebug() << "It is here 2";
    return true;
};

I tried writing the same thing in the mainwindow.cpp file and it worked just as it should. In the case of requests from the ping() function of my class, I don't see any requests in server logs. If everything is the same from mainwindow.cpp I see the request in the logs. What is the problem, and why it does not send the request?


Solution

  • As @Botje said, the problem was that QRestClient object is being destroyed at the end of calling code, before it is get the response. The solution is to put it in the private attributes of calling class.