1. 程式人生 > 其它 >https://stackoverflow.com/questions/3794649/qt-events-and-signal-slots

https://stackoverflow.com/questions/3794649/qt-events-and-signal-slots

https://stackoverflow.com/questions/3794649/qt-events-and-signal-slots

 

Events are dispatched by the event loop. Each GUI program needs an event loop, whatever you write it Windows or Linux, using Qt, Win32 or any other GUI library. As well each thread has its own event loop. In Qt "GUI Event Loop" (which is the main loop of all Qt applications) is hidden, but you start it calling:

QApplication a(argc, argv);
return a.exec();

Messages OS and other applications send to your program are dispatched as events.

Signals and slots are Qt mechanisms. In the process of compilations using moc (meta-object compiler), they are changed to callback functions.

Event should have one receiver, which should dispatch it. No one else should get that event.

All slots connected to the emitted signal will be executed.

You shouldn't think of Signals as events, because as you can read in the Qt documentation:

When a signal is emitted, the slots connected to it are usually executed immediately, just like a normal function call. When this happens, the signals and slots mechanism is totally independent of any GUI event loop.

When you send an event, it must wait for some time until the event loop dispatches all events that came earlier. Because of this, execution of the code after sending event or signal is different. Code following sending an event will be run immediately. With the signals and slots mechanisms it depends on the connection type. Normally it will be executed after all slots. Using Qt::QueuedConnection, it will be executed immediately, just like events. Check all connection types in the Qt documentation.