QNetworkAccessManager - 完成的信号永远不会触发插槽

时间:2014-07-26 17:04:48

标签: qt qnetworkaccessmanager qnetworkreply

我正在尝试使用QNetworkAcessManager来获取网址的来源。 但似乎信号槽复合体存在问题!

我的onFinished(QNetworkReply*)永远不会被触发!为什么呢?

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();
}

修改

正如“Oleg Shparber”所述,这是我的新代码(也不起作用):

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();
}

1 个答案:

答案 0 :(得分:2)

在控件到达start()方法结束后,您的QNetworkAccessManager会立即被破坏(有关详情,请参阅RAII)。您需要动态创建QNetworkAccessManager并在请求执行时保持活动状态。

此外,您正在连接不存在的信号。有QNetworkReply::finished(),但没有QNetworkReply::finished(QNetworkReply*)。如果您需要指向QNetworkAccessManager::finished(QNetworkReply*)的指针,也可以使用QNetworkReply