3

I'm trying to use QNetworkAcessManager to get the source of a url .. But it seems that there's a problem with the signal-slot complex!

my onFinished(QNetworkReply*) is never triggered! Why?

void Worker::start(QString url)
{
    QNetworkAccessManager manager;
    QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(url)));
    QObject::connect(reply, SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
}

void Worker::onFinished(QNetWorkReply * reply)
{
    qDebug() << "Slot has been triggered!";

    QString html = reply->readAll();
}

Edit:

As "Oleg Shparber" stated, here's my new code ( which also doesn't work ):

void Worker::start(QString url)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(url)));
    QObject::connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));


void Worker::onFinished()
{
    qDebug() << "Slot has been triggered!";

    QString html = reply->readAll();
}
Alaa Salah
  • 1,047
  • 3
  • 12
  • 28
  • I have changed my answer accordingly to your question update. – Oleg Shparber Jul 26 '14 at 18:25
  • @OlegShparber Thank you so much .. I was going to notify you that it was a minor mistake :) – Alaa Salah Jul 26 '14 at 19:17
  • Been a while since you posted this. But are you sure your Worker object itself hadn't been deleted before the request can get to it? *(That's what happened to me... a stack allocated object submitting the request and expecting to get a response, but it was gone by the time the request came back...)* FYI. – HostileFork says dont trust SE Jan 15 '15 at 08:27

1 Answers1

2

Your QNetworkAccessManager is destructed immediately after control reaches the end of the start() method (See RAII for details.). You need to create QNetworkAccessManager dynamically and keep it alive while request is performing.

Also, you are connecting to nonexistent signal. There is QNetworkReply::finished(), but no QNetworkReply::finished(QNetworkReply*). You can also use QNetworkAccessManager::finished(QNetworkReply*) if you need a pointer to QNetworkReply.

Oleg Shparber
  • 2,732
  • 1
  • 18
  • 19
  • Even when I used `QObject::connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));` and changed my slot's prototype to `void Worker::onFinished()` nothing happens also. Why? – Alaa Salah Jul 26 '14 at 19:16
  • 1
    Thanks you for helping me budd :) ... I've created `QNetworkAccessManager` dynamically, changed my slot, but nothing seems to work :( – Alaa Salah Jul 26 '14 at 20:01