问题
I'm trying to write a Qt
app that calls a web service. This is a console app, and url will be passed in as a command line argument. I searched for example http
programs in Qt
and found this link:
http://qt-project.org/doc/qt-5/qnetworkaccessmanager.html
Here it has the following code example:
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://qt-project.org")));
Now, if I take this and paste it into my console app, in main
, I obviously get build errors because this
does not exist. I get :
invalid use of 'this' in non-member function
Is there an equivalent QNetworkAccessManager
for non-GUI/console type apps?
回答1:
"this" is the this pointer of an object, so in main.cpp it causes errors, you should write some class where you will work with network and after that use this class in main function
It should be something like this. When you run app, you'll get html code of Qt site
It is just example, in future we can add here constructot, destructor, maybe signals(signals help us communicate with for example other classes if we need this)
*.h
#ifndef NET_H
#define NET_H
#include <QObject>
#include <QtCore>
#include <QNetworkAccessManager>
#include <QNetworkReply>
class Net : public QObject
{
Q_OBJECT
QNetworkAccessManager *manager;
private slots:
void replyFinished(QNetworkReply *);
public:
void CheckSite(QString url);
};
#endif // NET_H
*.cpp
#include "net.h"
void Net::replyFinished(QNetworkReply *reply)
{
qDebug() << reply->readAll();
}
void Net::CheckSite(QString url)
{
QUrl qrl(url);
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(qrl));
}
main
#include "net.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Net handler;
handler.CheckSite("http://qt-project.org");
return a.exec();
}
来源:https://stackoverflow.com/questions/25433706/qt-console-app-using-qnetworkaccessmanager