I have a Qt application with this kind of main()...
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWin;
... A separate, non-GUI thread is launched here
mainWin.Init();
mainWin.show();
app.exec();
}
This other thread that is created before the mainWin needs to know when it can start communicating with the mainWin. But since the mainWin uses Qt signals, slots, timers, etc, it's not truly ready to rock until the event loop is running (via exec()).
My question is: is there some signal or event that is emitted when the event loop has started?
Consider this. In mainWin.Init(), you can create something like a QTimer and even call .start() to kick it off. But it won't actually be run and trigger events until exec() has been called. This is why I need to know when the event loop has truly started.
An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such as QTimer, QTcpSocket, and QProcess). It also makes it possible to connect signals from any threads to slots of a specific thread.
In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.
Qt's event loop starts the moment the underlying application's exec() function gets called. Once started, the loop repeatedly checks for something to happen in the system, such as user-input through keyboard/mouse.
This ensures that truly independent components can be created with Qt. You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal.
You can send a signal to your window before the exec()
call. This will place an entry in app
's signal queue.
When exec()
is running, the signal will be delivered and your window will know that the event loop is running.
A simple way would be to use QTimer::singleShot(0, &mainWin, SLOT(onEventLoopStarted()));
which connects to a custom slot of your window class.
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