Home > other >  Communicate between two widgets not directly related
Communicate between two widgets not directly related

Time:07-19

I have a GUI with widgets that has multiple child widgets inside, as you can see in the image:

enter image description here

I want to communicate "Widget 2-2" with "Widget 1-1". I have different options, but I don't know which is better.

1. Propagate signal

My first idea was propagates the emit to Main Windows and then it propagates the action to the target widget:

  1. Widget 2-2 emits a signal
  2. Widget 2 catch the emit and emit anther signal
  3. Main Windows catch the emit and call a Widget 1 controller function
  4. Widget 1 controller function calls a Widget 1-1 controller function
  5. Widget 1-1 makes the action

Pros

  • All the widgets only talks with its parents and children

Cons

  • It can be a bit messy

2. Create a singleton class with all the signals

Another idea is to create the signals in a singleton class. Then the Widget 2-2 can emit this signals easily and Widget 1-1 can listen this signals easily too. The relative position of the widgets in the architecture does not care, everybody can emit and connect the signals.

Pros

  • Emit and connect this signals is super easy. Everybody can do it.

Cons

  • I feel that it is a super bad idea. Probably it will explode in the future, but I don't know why. I prefer to follow the best practices than solve my problem fast and easily (for the moment...)

CodePudding user response:

Singletons, or static initialisation for that matter ought to be the last resort as they can cause all sorts of headaches, especially in multi-threaded environment. Definitely do not go for that in this case.

What I have personally done in my project in this case, I emitted a signal in the first widget and then forwarded that in the first common parent to the second widget so that the second widget handled it via its slot in there.

This has worked fairly well for me, at least. You can forward signals just fine in Qt, i.e. connect a signal to a signal.

The first common parent will encompass both, so you can use it as a proxy for managing the two, or potentially even more widgets in your architecture.

  • Related