Qt: Is there notification when event loop starts?

蓝咒 提交于 2021-02-07 04:54:25

问题


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.


回答1:


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.




回答2:


Since emitted signals don't get lost when the event loop is not yet running, your thread may not necessarily need to know when your window is ready.
Your thread could start sending signals to the window right away but it will only receive signals from the window when the event loop is running.




回答3:


You can do it in the following order:

QApplication app(argc, argv);
Mainwinwdow mainWin;
QThread yourThread;

//connect the signals from the thread to the mainWin here

mainWin.Init();
mainWin.show();

yourThread.start();

return app.exec();


来源:https://stackoverflow.com/questions/8876390/qt-is-there-notification-when-event-loop-starts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!