Reputation: 1
I'm trying to use QNetworkaccessmanager which i get working, but only when I use it basic generated main class. It doesn't work from any other class like mainwindow.
main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
Updater up;
up.Update();
return a.exec();
}
updater.cpp
#include "Updater.h"
Updater::Updater(QObject *parent) :
QObject(parent)
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(replyFinished(QNetworkReply*)));
}
void Updater::Update()
{
manager->get(QNetworkRequest(QUrl(//url)));
}
void Updater::replyFinished (QNetworkReply *reply)
{
if(reply->error())
{
qDebug() << "ERROR!";
qDebug() << reply->errorString();
}
else
{
QString result = (QString)reply->readAll();
//foo(result)
}
reply->deleteLater();
}
Upvotes: 0
Views: 256
Reputation: 8708
There is number of ways you can reuse the instance of class across your app code and for instance the singleton pattern:
// TODO: Provide Updater* updater() in the header file
// and use it like updater()->Update(); wherever you like
// in your application class' objects
static Updater* s_updater;
Updater* updater()
{
return s_updater;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
Updater up;
s_updater = &up;
// do this from somewhere else
// up.Update();
return a.exec();
}
The problem with this approach is to how deliver the results to certain consumer but that is a separate question and it is not even clear if you want it or the way it works is Ok but just this object needs to be callable across your app code.
Also, some of software engineers dislike the singleton pattern (there reasons for that though arguably that is so bad) and you can simply create the object dynamically with new operator but make sure you manage its life cycle properly. There is also number of ways to do so in Qt: passing the object parent to constructor of QObject derived class, QScopedPointer, QSharedPointer, etc.
Upvotes: 0