Reputation: 325
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?
If I create the childWidget in the mainWidget's constructor and place
the connect statement on the next line, it works. But, let's say the
childWidget, upon being created, does something and then signals to
the mainWidget success. You could have a situation where the connect
statement only comes after a function (of childWidget) that emits the
signal.
If I place the connect statements in the childWidget's constructor,
the problem is that it doesn't know anything about the parent's
slots. If I make childWidget inherit mainWidget, it does know about
the slots - but this feels like a bad solution to me. Couldn't get it
to work anyway. There is probably a proper way to do this - I'm still
looking.
I'm quite new to Qt programming. In advance: thank you for any help.
Upvotes: 3
Views: 2715
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
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