Reputation: 6886
I want to achieve to download a file in a separate thread and store that file, but I was not able to find an appropriate way to achieve this without evil delay (quite frequent download of small files, so signal+slots are too slow). What I want to achieve: (Pseudo Code)
request file;
wait for download finishing, timeout or error;
save downloaded file;
I'd prefer an example with QNetworkAccessManager if possible. Thanks for any tipp.
Edit: Just to be clear, I want signal and slots not because of design aswell as the lack of speed.
Edit2: This download is only about the download file in sync part, threading is no problem. The problem is that QT does not provide an api for doing that and I am not keen on hotspinning wait.
Edit3: Example code like it should work, but does not:
QNetworkAccessManager net;
QNetworkReply *re (net.get( QNetworkRequest( QUrl( Qstring("www.blah.org/key") ) ) ));
if (re->waitForReadyRead(-1)) //! @bug this does not work as supposed, waitForRead returns false and returns INSTANTLY!!
qDebug() << "ReadyRead yeha!!!";
if (re->error()) {
qDebug() << "Can't download" << re->url().toString()
<< ":" << re->errorString();
} else {
img->load(re->readAll());
qDebug() << "Savin IMG";
}
delete re;
Upvotes: 2
Views: 3781
Reputation: 9
Sync Network access is a bad idea because it makes bad UI experience. Besides what you think is a bug is not a bug. It is just wrongly documented.
Upvotes: 0
Reputation: 20881
I needed something similar but for different reasons. Since QHttp and QNetworkAccessManager are both async what you could do is use a separate event loop, a full example based on QHttp can be found here. It shouldn't be too difficult to modify it for QNetworkAccessManager.
It's worth mentioning that your impression that signals/slots are "slow" is probably wrong. Have you actually profiled your code to determine this?
Whatever penalty you might be paying for signals/slots it's probably negligible when looking at the amount of time a single file download takes. More so, it's very "non Qt" to do things this way. These classes were designed like this for a reason.
At the end of the day if you are indeed suffering from signals/slots (which is again, doubtful), I would recommend not to use Qt for this particular task, maybe plain old C sockets are a better idea (or a thin wrapper around them to save the error handling which might require some extra work).
Upvotes: 1