After 18 months ... I started with comments under @Mat's answer, and was running out of room quickly. Thus the answer.
IMO emit
is neither syntactic sugar nor a simple keyword in the sense that
- It generates code (as explained by @Mat above),
- It helps the
connect
mechanism recognize that indeed it is a signal
, and
- It makes your signal part of a "bigger" system, where signals and responses (slots) can be executed synchronously or asynchronously, or queued, depending on where and how the signal got emitted. This is an extremely useful feature of the signal/slot system.
The entire signal/slot system is a different idiom than a simple function call. I believe it stems from the observer pattern. There is also a major difference between a signal
and a slot
: a signal does not have to be implemented, whereas a slot must be!
You are walking down the street and see a house on fire (a signal). You dial 911 (connect the fire signal with the 911 response slot). The signal was only emitted, whereas the slot was implemented by the fire department. May be imprecise, but you get the idea. Let's look at the example of OP.
Some backend object knows how much progress has been made. So it could simply emit progressNotification(...)
signal. It is up to the class that displays the actual progress bar, to pick up this signal and execute on it. But how does the view connect to this signal? Welcome to Qt's signal/slot system. One can now conceive of a manager class (typically a widget of sorts), which consists of a view object and a data computation object (both being QObjects
), may perform connect (m_myDataEngine, &DataEngine::progressNotification, m_myViewObj, &SimpleView::displayProgress)
.
Let's not get into the design aspects of the manager class, but suffice it to say that this is where signal/slot system shines. I can focus on designing a very clean architecture for my application. Not always, but often times, I find that I merely emit signals but implement slots.
If it is possible to use/call a signal method without ever emitting it, then it necessarily implies that you never needed that function as a signal in the first place.
emit
is not needed. It's strange though, that you learned aboutemit
long after calling signals directly, as the signal-slot system is one of the first things to be learned about Qt. – Christian Rau