PDA

View Full Version : Help: Signals/slots system



0xl33t
23rd July 2009, 22:47
Hey, how do you connect a signal from a child widget with a slot from the parent widget?

1) I have a MainWindow, and i want to connect the newAction (QAction)
2) the central widget of my main window is a stackedWidget which contains the child widget i want to connect
3) the child widget is a customWidget with a public slot, called foo()

See the attached image...

i tried with this from stackedWidget, which is between(child & parent) mainwindow-customwidget:
connect(parentWidget()->newAction, SIGNAL(triggered()), customWidget, SLOT(foo()));

i get an error saying that QWidget doesn't have a member called newAction()....

So, in short how to connect a child's slot with a parent's signal?

thanks

franz
23rd July 2009, 22:59
The error is pretty clear I think. QWidget doesn't have a member called newAction (be it a function or a variable).

You can declare a new signal for your parent that you relay to the child:
in the parent:

connect(newAction, SIGNAL(triggered()), this, SIGNAL(newActionTriggered()));
and then in the intermediate:

connect(parent(), SIGNAL(newActionTriggered()), child, SLOT(foo()));

If you have a clear shot at the child widget from the parent, you could do:

connect(newAction, SIGNAL(triggered()), intermediate->child, SLOT(foo()));

Edit: typo.

wysota
23rd July 2009, 23:05
Or you can cast the parent widget to appropriate type (i.e. using qobject_cast) and make the connection directly.

0xl33t
23rd July 2009, 23:12
@Franz, THANKS, i didn't consider that solution! Now it works! yay!


Or you can cast the parent widget to appropriate type (i.e. using qobject_cast) and make the connection directly.

I never used qobject_cast, to which type do i have to cast the parentWidget? Isn't it already QWidget? Or did i understand wrong?

wysota
23rd July 2009, 23:38
You have to cast it to your widget type - the one that has "newAction" defined, which is probably "MainWidget".

MainWidget *mw = qobejct_cast<MainWidget*>(parentWidget());
Q_ASSERT(mw!=0);
connect(mw->newAction(), SIGNAL(triggered()), customWidget, SLOT(foo()));

0xl33t
24th July 2009, 08:57
You have to cast it to your widget type - the one that has "newAction" defined, which is probably "MainWidget".

MainWidget *mw = qobejct_cast<MainWidget*>(parentWidget());
Q_ASSERT(mw!=0);
connect(mw->newAction(), SIGNAL(triggered()), customWidget, SLOT(foo()));

yes that works too!! Thanks! Now i can create connections without limits :P

thx :D