Qt intercept Application::exec in the application class?
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 star开发者_如何学Pythont 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
?
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.
}
精彩评论