Search code examples
qtsignals-slots

Why does Qt use virtual functions in place of signals at times?


In QWidget, rather than being signals, mouse and paint and other events are virtual functions to be overloaded. Why is this the case, rather than being consistent?


Solution

  • Although I can't find anything within Qt's documentation that states their motivations for using virtual functions for events, I can guess:

    1. Signals and slots can be nice to work with, but there's overhead associated with them (see, the answer to this question). Since events are triggered quite frequently, the use of signals and slots could carry quite a performance penalty.
    2. Some event handlers need to return values. Returning a value from a slot back to the signal emitter is not officially supported (though see this question), which means that they wouldn't be appropriate.
    3. Signals emitted from QWidget may not make sense from a design point-of-view. If I create my own widget derived from QWidget, why have signals emitted from my widget that just connect back to slots within the widget itself? This also has the danger of breaking encapsulation since signals are always "public".

    Even if none of the above were true, there would still be quite a few architectural questions raised by trying to use signals for events. For example, a single event is often passed to multiple different objects (for example, in the case where some objects don't wish to process the event). In this scenario, which object emits the signal indicating that the event has taken place? It's certainly not the target of the event (i.e., the widget, as you've implied above). It would have to be some other global object. But if that were true, we would likely just implement virtual slots on every widget to handle the signal. This essentially just gets us back to where we started with virtual functions!