PDA

View Full Version : Which design is better for signal & slots connections?



nifei
6th May 2010, 05:04
I have 3 components, one of which is parent of the other 2. Say they are Parent and Child0 and Child1. All the 3 components can emit signal changed(). When one of the child emit changed(), Parent need to emit changed() and the other child need to call slot onChanged()

My question is, which would be better in the view of design?

design 1: connect signals of each child to the Parent's signal and slot of the other child.


connect(Child0, SIGNAL(changed()), Child1, SLOT(onChanged()));
connect(Child1, SIGNAL(changed()), Child0, SLOT(onChanged()));
connect(Child0, SIGNAL(changed()), this, SIGNAL(changed())); // this refers to Parent
connect(Child1, SIGNAL(changed()), this, SIGNAL(changed()));


design 2: connect signals of each child to a special slot, in which Parent will emit signal changed() and the other child call onChanged()


connect(Child0, SIGNAL(changed()), this, SLOT(onChildChanged()));
connect(Child1, SIGNAL(changed()), this, SLOT(onChildChanged()));
...

onChildChanged(){
if(sender() == Child0)
{
Child1->onChanged();
}
else if (sender() == Child1)
{
Child0->onChanged();
}
emit changed(); // this refer to Parent
}

aamer4yu
6th May 2010, 07:06
What do you want to achieve by the signals ?
If you tell the requirements, we might be able to suggest the design properly.

Lykurg
6th May 2010, 07:20
Use the first one. In the second the function is unnecessary and sender() breaks the OO design. If you will increase the numer of childs this could be less writing for you:
connect(Child0, SIGNAL(changed()), this, SIGNAL(changed())); // this refers to Parent
connect(Child1, SIGNAL(changed()), this, SIGNAL(changed()));
//... more childs here
connect(this, SIGNAL(changed()), Child0, SLOT(onChanged()));
connect(this, SIGNAL(changed()), Child1, SLOT(onChanged()));