Problems with eventloop in CLI application



  • I'm making CLI application in qt and I was doing fine until I needed to download some files from the internet. Slot connected to QNetworkAccessManager::finished wouldn't trigger unless I run qApplication.exec() at the end of my main function.

    So I did, but that created another problem

    int main(int argc, char **argv){
        QApplication qApplication(argc, argv);
        ClassForDownloading::download();
    
        doTheRestOfstuff();
    
        return qApplication.exec();
    }
    

    doTheRestOfStuff() waits for download to finish (i use QSemaphore for that), but because I need to call qApplication.exec() in order for download to start it waits forever.

    So I put restOfStuff into a Thread

    int main(int argc, char **argv){
        QApplication qApplication(argc, argv);
        ClassForDownloading::download();
    
        RestOfstuffThread *restOfStuffThread = new RestOfStuffThread();
        restOfStuffThread->start()
    
        return qApplication.exec();
    }
    

    And now everything works, except it never closes, even if I call QCoreApplication::quit(); or QCoreApplication::exit() inside of the thread.

    How do I handle qt Event Loop correctly?


  • Moderators

    @HalfTough Why don't you instead emit a signal when ClassForDownloading::download(); is finished which you then connect to a slot in another class which executes doTheRestOfstuff()? No need for any threads.
    This would be the way to do it in an event based application like Qt app. There is no need to "wait" for something, instead you simply react on events (signals).
    Something like

    int main(int argc, char **argv){
        QApplication qApplication(argc, argv);
    
        ClassForDownloading downloading;
        ClassTodoStuff stuff;
        connect(&downloading, SIGNAL("finished()"), &stuff, SLOT("doTheRestOfstuff()"));
        downloading.download();
    
        return qApplication.exec();
    }

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.