Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct Qt idiom for exposing signals/slots of contained widgets?

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:

  1. Expose a pointer to the MySubWidget instance through a subWidget() method in MyWidget
  2. Duplicate the signals and slots of MySubWidget in the MyWidget class and write "forwarding" code
  3. Something else?

Choice 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?

like image 512
Tyler McHenry Avatar asked Apr 01 '10 00:04

Tyler McHenry


People also ask

What is signals and slots in Qt?

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.

How Qt slots work?

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.

What are signals and slots in Python?

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 .


1 Answers

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.

like image 104
richardwb Avatar answered Oct 05 '22 18:10

richardwb