AJO_
AJO_

Reputation: 325

Qt: Where to place a connect statement?

I have a widget (mainWidget) and another widget (childWidget), that's a child of it.

I want to:

connect(childWidget, SIGNAL(somethingHappened(...)), mainWidget, SLOT(handleIt(...));

My question is: does one place the connect statement in mainWidget or childWidget?

I'm quite new to Qt programming. In advance: thank you for any help.

Upvotes: 3

Views: 2715

Answers (2)

JustMaximumPower
JustMaximumPower

Reputation: 1277

I always do the connect calls after the construction of the object inside the class that created the child. The reason is simple: The object creating the child knows what signal/slot the child has and which it needs for its purpose, but the child can't and more importunity shouldn't know. If the child has more expectations about its parent than necessary you will limit the reusability of your code.

You are right that signals in constructors won't be heard by anyone. Just don't use signals in constructors the same way one shouldn't use virtual functions in constructors. If you have to emit signals upon initialization write a separated ini function and call it after connect.

You could also use qobject_cast to determine the type of the parent at run time, but that is just bad design.

Upvotes: 2

mots_g
mots_g

Reputation: 637

You should design your code well to avoid creeping of mysterious bugs. It would be a better idea to write the connect in the main widget and ideally there should not be an emit in the constructor of the child widget. Possibly you could move out the emit code to another block and do the call after construction is complete. Sub-classing 'childwidget' from 'mainWidget' only to get access to its slot looks like an inflexible design. Design should be such that if any class knows the signal your class emits, the other class should be able to flexibly connect to it.

Upvotes: 2

Related Questions