QEventLoop proper usage

后端 未结 2 1547
慢半拍i
慢半拍i 2021-02-15 16:25

I have doubts how should I use QEventLoop. I have 2 pieces of code, both of them work for me (get web resource downloaded).

First one:

QN         


        
2条回答
  •  甜味超标
    2021-02-15 16:38

    In your second example event loop will never quit, on the other hand in your first example the loop will quit when finished(QNetworkReply*) emits. But what if manager->get( request ); cause finished(QNetworkReply*) signal to be emited before you connect loop's quit to it?

    QNetworkAccessManager *manager = new QNetworkAccessManager( this );
    QNetworkRequest request;
    QEventLoop loop;
    request.setUrl(QUrl(url));
    request.setRawHeader("User-Agent", "Mozilla Firefox");
    connect(manager, SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
    connect(manager, SIGNAL(finished(QNetworkReply*)),&loop, SLOT(quit()));
    manager->get( request )  ;
    
    loop.exec();
    

    And also you need to somehow handle situation where manager does not emit SIGNAL(finished(QNetworkReply*)) at all.

提交回复
热议问题