As described here, you can connect a signal to a simple function, like this:
connect(
sender, &Sender::valueChanged,
someFunction
);
Here is my program:
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
void handleReply(QNetworkReply *reply)
{
QString replyStr = reply->readAll();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager manager;
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
return a.exec();
}
However, I get a few errors:
main.cpp:18: error: call to non-static member function without an object argument
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
main.cpp:18: error: 'QNetworkReply' does not refer to a value
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
main.cpp:18: error: expected expression
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
main.cpp:18: error: 'QNetworkReply' does not refer to a value
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
/usr/include/x86_64-linux-gnu/qt5/QtNetwork/qnetworkreply.h:62: declared here
class Q_NETWORK_EXPORT QNetworkReply: public QIODevice
main.cpp:18: error: expected expression
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
^
When you use the new connection syntax it is not necessary to indicate the type of arguments, so just use:
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QDebug>
static void handleReply(QNetworkReply *reply)
{
QString replyStr = reply->readAll();
// do stuff
qDebug()<< replyStr;
reply->deleteLater();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager manager;
QObject::connect(&manager, &QNetworkAccessManager::finished, &handleReply);
manager.get(QNetworkRequest(QUrl("https://www.google.com")));
return a.exec();
}
Note:
You should only use connect(...)
if you are inside a class that inherits from QObject
, in the case of main you should use QObject::connect(...)