Hi! I'm newb to Qt and got stuck in a signal/slot mechanism. I have a toolbar with a number of tool buttons, each associated with some widget. The task is to show appropriate widget when tool button is clicked. I want to write a single slot that will handle the associations, but I can't figure out how to distinguish what button triggered a signal. It seems that clicked and toggled signals of QToolButton accept only no-argument slots and store no information about their emitter. I can subclass QtoolButton and raise a CLR event with information about the event sender on each clicked or toggled signal emission, but there should be simplier way to do what I want. Can you help me?
A:
In your slot, you should be able to call the function sender()
, which would return a pointer to the object that emitted the signal (if any did... remember, you can call slots just like a function as well). This is the quick, relatively easy, and sloppy way. However, it breaks encapsulation.
A slightly better way would be to provide a numbering mechanism for the buttons, and use a QSignalMapper
to map the individual buttons into one signal that contains an int for the button that was clicked.
This is in C++ (which I'm more familiar with):
QSignalMapper *mapper = new QSignalMapper( this );
connect( mapper, SIGNAL( mapped( int ) ), SLOT( MyFancyFunction( int ) ) );
// Do this for each button:
mapper->connect( button1, SIGNAL( clicked() ), SLOT( map() ) );
mapper->setMapping( button1, FIRST_TOOL )
Then:
void MyFancyFunction( int option )
{
switch ( option )
{
case FIRST_TOOL: // do whatever...
}
}
Caleb Huitt - cjhuitt
2009-07-16 18:38:20