Is there some way to have a function in my application class (derived from QApplication) called when QCoreApplication::exec()
is called? I don't see any signal or event that is generated just prior to the message loop starting.
I have various components to be created that depend on a fully constructor application object. In turn, some other components need to be created after those components (as they rely on them) -- these however are the primary dialogs in the application, so something has to start them.
Currently I just post a queued signal from the application constructor, which is then processed once the event loop starts. I'm just wondering if there is a clearer way to intercept exec
?
[static] int QApplication::exec() Enters the main event loop and waits until exit() is called, then returns the value that was set to exit() (which is 0 if exit() is called via quit()). It is necessary to call this function to start event handling.
QApplication specializes QGuiApplication with some functionality needed for QWidget-based applications. It handles widget specific initialization, finalization. For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time.
this is an old technique in gui applications but it might work for you.
use QObject::startTimer(0)
then reimplement QObject::timerEvent() to have the various components that rely on a fully constructed application object
. By doing so, the various components that rely on a fully constructed application object
will only be created once the event loop starts.
a little bit of explanation: QObject::startTimer(int ms) is a function that runs a timer in milliseconds that fires every ms. If you pass "0" as an argument, then it fires as soon as the event loop starts. once it fires, it calls QObject::timerEvent() in the same class QObject::startTimer() was called. make sure you stop the timer with QObject::killTimer() inside your reimplementation of QObject::timerEvent() or else the timer will fire infinitely.
but @Mat has a point, just because the event loop has not started, does not mean the QCoreApplication is not fully constructed. Try and have a look at this.
{
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With