Suppose I have a MyWidget
which contains a MySubWidget
, e.g. a custom widget that contains a text field or something. I want other classes to be able to connect to signals and slots exposed by the contained MySubWidget
instance. Is the conventional way to do this:
MySubWidget
instance through a subWidget()
method in MyWidget
MySubWidget
in the MyWidget
class and write "forwarding" codeChoice 1 seems like the least code, but it also sort of breaks encapsulation, since now other classes know what the contained widgets of MyWidget
are and might become dependent on their functionality.
Choice 2 seems like it keeps encapsulation, but it's a lot of seemingly redundant and potentially convoluted code that kind of messes up the elegance of the whole signals and slots system.
What is normally done in this situation?
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.
The Qt signals/slots and property system are based on the ability to introspect the objects at runtime. Introspection means being able to list the methods and properties of an object and have all kinds of information about them such as the type of their arguments.
Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. Signals and slots are made possible by Qt's meta-object system .
If you look at Qt's own code they prefer option 2.
For example, look at QTabWidget and QTabBar. They share a number of signals and slots, yet QTabWidget hides the fact that it uses a QTabBar (well, sorta... QTabWidget::tabBar()
obviously breaks this even though it's protected).
Although this will result in more code, I think it's worth it for the encapsulation.
Don't forget that you can connect signals to signals like so:
connect(mySubWidget, SIGNAL(internalSignal(int)), this, SIGNAL(externalSignal(int)));
Which will make MyWidget
emit externalSignal(int)
when MySubWidget
emits internalSignal(int)
. This helps with the signal side of things at least. I don't know of any easy way to do the same for slots, unfortunately.
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