10-30-2012 05:36 AM
I have an array multiple buttons created and assigned to specific function.
But I would like to know which button the user pressed. Any idea?
How should I implement the Signal and Slots
for(int i=0;i<8;i++)
{
button[i]= Button::create();
buttonContainer->add(button[i]);
QObject::connect(button[i], SIGNAL(clicked()), this, SLOT(doStuffs()));
}
Solved! Go to Solution.
10-30-2012 07:53 AM - edited 10-30-2012 07:56 AM
Use QObject::sender() in your slot and cast the result to Button. If you first do "button[i].tag = i" then you can find out in the slot exactly which button was triggered. Unfortunately, you first need to subclass Button and include an integer tag value. I've already filed a feature request about this.
10-30-2012 11:55 PM
Perfect, thanks!!!
10-31-2012 01:44 AM
You also may want to look up QSignalMapper:
http://qt-project.org/doc/qt-4.8/qsignalmapper.htm
Its a utility class that's part of Qt, which is designed to help with this exact situation.
10-31-2012 03:42 AM
Well, code doesn't become more beautiful this way. I still like my tag solution better. But thanks for telling us about it. It might come in handy sometime, especially in more complex cases that canot be handle with a simple tag value.
10-31-2012 10:07 AM
Actually, QSignalMapper is just a simpler way of implementing the tag approach. The only difference is that you configure the tags in the QSignalMapper setup, instead of the buttons themselves, and the tag values are delivered right along with the signal parameters. (so no need to check sender() or anything)