tags:

views:

435

answers:

1

Hi 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;
+1  A: 

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).

Idan K
Well I hoped not having to use exec() in the parallel thread.You got me an idea :-D thank you
penguinpower
ok after 3hours of searching I stumbbled accross this:http://wiki.qtcentre.org/index.php?title=Keeping_the_GUI_Responsiveand it suggests the same way you suggested me, and I did it that way and it works. Thank you. You solved it :-)
penguinpower