gpt4 book ai didi

c++ - QNetworkAccessManager 问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:17 25 4
gpt4 key购买 nike

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 更新它的情况下以这种方式返回的。等待工作完成的解决方案是什么,这样我就可以获得正确的信息,而不是跳过它并返回其他东西。谢谢。

最佳答案

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

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;

}

关于c++ - QNetworkAccessManager 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24285021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com