I work in a team to develop a QT Application with c++. Among other things, the app needs to download files from the internet. Here is the code I wrote to download files:
int main(int argc, char *argv[]){
QCoreApplication app(argc, argv);
QNetworkAccessManager man;
std::string urlc = "https://upload.wikimedia.org/wikipedia/commons/7/73/Flat_tick_icon.svg"; //Ramdom svg file
QUrl url(QString::fromStdString(urlc));
QNetworkRequest req(url);
QNetworkReply* reply = man.get(req);
QObject::connect(reply, &QNetworkReply::finished, [department, region, &reply](){
QByteArray read = reply->readAll();
QString savefile = QString::fromStdString("file.png");
QFile out(savefile);
out.open(QIODevice::WriteOnly);
out.write(read);
out.close();
reply->close();
reply->deleteLater();
app.quit();
});
return app.exec();
}
The above code works well and downloads the file at the specified url. However, if I try to extract the downloading of files to a separate function (see code below), the program doesn't work. In fact, it never even starts downloading the file.
std::string download_file(){
QNetworkAccessManager man;
std::string urlc = "https://upload.wikimedia.org/wikipedia/commons/7/73/Flat_tick_icon.svg"; //Ramdom svg file
QUrl url(QString::fromStdString(urlc));
QNetworkRequest req(url);
QNetworkReply* reply = man.get(req);
QObject::connect(reply, &QNetworkReply::finished, [department, region, &reply](){
QByteArray read = reply->readAll();
QString savefile = QString::fromStdString("file.png");
QFile out(savefile);
out.open(QIODevice::WriteOnly);
out.write(read);
out.close();
reply->close();
reply->deleteLater();
});
return "file.png";
}
int main(int argc, char *argv[]){
QCoreApplication app(argc, argv);
std::string path = download_file();
std::cout << path << std::endl;
return app.exec();
}
What can be the reason for such behaviour?
Aucun commentaire:
Enregistrer un commentaire