1
QString My_class::My_Method()
{
    QNetworkAccessManager *manager= new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ReplayFinished(QNetworkReply*)));
    manager->get(QNetworkRequest(QUrl(My_URL)));
    return str;
}

void My_class::ReplayFinished(QNetworkReply *replay)
{
    QString buffer;
    if(replay->isOpen())
    {
        buffer=replay->readAll();
//treatment on the buffer and the public Qstring 'str'(declared in My_class.h) is updated
    }
}

嗨,问题是在 main 中调用 My_method() 时,QString str它是空的,因为它是以这种方式返回的,而无需等待 ReplayFinished 更新它。等待工作完成的解决方案可能是什么,以便我可以获得正确的信息,而不是跳过它并返回其他内容。谢谢你。

4

1 回答 1

2

您可以使用事件循环等待回复完成,然后读取可用字节并返回字符串:

QString My_class::My_Method()
{

   QNetworkAccessManager manager;

   QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(My_URL)));

   QEventLoop loop;
   connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
   connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit()));
   loop.exec();

   QByteArray bts = reply->readAll();
   QString str(bts);

   delete reply;

   return str;

}
于 2014-06-18T12:06:00.133 回答