Trick of the day: prefetching a callback into the QApplication event loop


Qt provide a standard mechanism (aboutToQuit() signal) to insure that a callback is executed at the end of the QApplication event loop. This is typically used to add some cleanup code to your application.


Infortunately, Qt does not provide a “aboutToRun()” if you want to execute an initializing code just before the event loop.


Nevertheless this small trick using a QTimer allows you to stack a callback in the event loop. The callback be executed at the start of the QApplication::start() call.



class myApplication : public QApplication
{
    Q_OBJECT
 public:
    myApplication(int& argc, char **argv);
   ~myApplication(void);
 
 public slots:
   void preExecutionLoop(void);
   void postExecutionLoop(void);
}

myApplication::myApplication(int& argc, char **argv) : QApplication(argc, argv)
{
    // some data initialisation
    ....

    //  --- here is the trick ---
    // the preExecutionLoop() callback will be called at the entrance of myApplication::exec()                                                                
    QTimer::singleShot(0, this, SLOT(preExecutionLoop()));

    // just for the record: 
    // the postExecutionLoop() callback will be called at the exit of myApplication::exec()              
    QObject::connect(this, SIGNAL(aboutToQuit()), this, SLOT(postExecutionLoop()));
}


Leave a Reply

Your email address will not be published. Required fields are marked *