Qt synchronous QNetworkAccessManager get

10,734

Solution 1

Yum may use something like this:

QEventLoop loop;
connect(_netReply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();

Solution 2

The simple solution mentioned in the wiki and in the answer from yttrium is quite fragile since it doesn't handle all possible failure scenarios (such as proxy) and therefore shouldn't be used in a production environment, and unfortunately it has become quite prolific, so anyone asking for synchronous QNAM simply get stumped by "use it asynchronoysly [stupid]" or this simple piece of code that will eventually fail.

I haven't found a "proper" solution made by the Qt team themselves, but this guy on codeproject has been decent enough to make a more comprehensive wrapper that should be a lot safer:
http://www.codeproject.com/Articles/484905/Use-QNetworkAccessManager-for-synchronous-download

Share:
10,734

Related videos on Youtube

Eugene
Author by

Eugene

Updated on June 04, 2022

Comments

  • Eugene
    Eugene almost 2 years

    What's the proper way to do a synchronous QNetworkAccessManager::get ?

    The qt wiki offers an approach, but states "it is not recommended to use this in real applications." The mailinglist offers a similar solution to the wiki.

  • Raiden Core
    Raiden Core almost 8 years
    I did this easily in python, in GUI, and in production system, why things (synchronous use of QNAM) are not formal and easy in Qt ?
  • nurgasemetey
    nurgasemetey over 7 years
    @RaidenCore , also asking same question. Is it related with C++?
  • fyngyrz
    fyngyrz almost 6 years
    @RaidenCore , It's not related to c++. This is a (major) shortcoming of Qt itself. There's no good reason one could not have a proper inline synchronous download with a preset potential timeout, etc. This is one of those things where in trying to provide a general solution to everything, the simple and obvious use case becomes a nightmare.
  • fyngyrz
    fyngyrz almost 6 years
    @RadenCore , continuing, what you can do is call an external program to do the download for Qt, for instance, a simple Python script, the wget command, etc. There is literally no need for this simple task to be this hard.
  • 1337user
    1337user almost 6 years
    There is a good reason why they make synchronous I/O "hard" and that is simply because it gets abused all them time in settings where you shouldn't do blocking operations. Just look at JS, there they've even gone as far as removing the sync API because it gets too much abuse. Qt makes it fairly easy to work with an event loop and async messaging, but still there should be a bit more helper functions and/or a good example on how to do this in scenarios where you just need a simple sync I/O (which is quite seldom in large applications with user interaction).