Qt intercepts Application :: exec in an application class?

Is there a way to have a function in my application class (derived from QApplication) called when QCoreApplication::exec() called? I do not see any signals or events that are generated immediately before starting the message loop.

I have various components to be created that depend on the object object of the fully constructor. In turn, some components must be created after these components (because they rely on them) - however, these are the primary dialogs in the application, so something should start them.

Currently, I just send a message to the queue from the application constructor, which is then processed after the event loop starts. I'm just wondering if there is a clearer way to intercept exec ?

+7
source share
1 answer

This is an old technique in gui applications, but it may work for you.

use QObject::startTimer(0) , then override QObject :: timerEvent () to have various components that rely on a fully constructed application object . By doing so, various components that rely on a fully constructed application object will be created only after the event loop starts.

a little explanation: QObject :: startTimer (int ms) is a function that starts a timer in milliseconds that fires every millisecond. If you pass "0" as an argument, it starts as soon as the event loop begins. once it fires, it calls QObject :: timerEvent () in the same class QObject :: startTimer (). make sure you stop the timer with QObject :: killTimer () inside your reimplementation of QObject :: timerEvent (), otherwise the timer will run indefinitely.

but @Mat has a point, just because the event loop is not running yet, does not mean that QCoreApplication is not fully constructed. Try it and look at it.

 { QApplication app(argc, argv); //this is already a fully contructed QApplication instance MyClass *myObject = new MyClass; //this relies on a fully constructed QApplication instance return app.exec(); //this starts the event loop as you already know. } 
+1
source

All Articles