June 14, 2012

Endless Endless
Lab Rat
82 posts

[Solved] Differentiating multiple signals going to a single slot

 

Here’s some code that creates a list of 10 pushbuttons and connects the clicked singal of all of them to a single slot (on_pushButtonList_clicked)

  1.     for(index = 0; index < 10; index++)
  2.     {
  3.         pushButton[index] = new QPushButton(this);
  4.         pushButton[index]->resize(60, 40);
  5.         pushButton[index]->move(400, 50 + 50 * index);
  6.         pushButton[index]->setText(QString::number(index, 'g', 2));
  7.         connect(pushButton[index], SIGNAL(clicked()), this, SLOT(on_pushButtonList_clicked()));
  8.     }

When I get to the on_pushButtonList_clicked slot, how do I find out which button was clicked? In addition to getting a pointer to the button that was hit, is there a way to get its index position (pushButton0, pushButton6, etc.)?

2 replies

June 14, 2012

mlong mlong
Mad Scientist
1517 posts

Check out QSignalMapper. [qt-project.org]

 Signature 

Senior Software Engineer
AccuWeather Enterprise Solutions
/* My views and opinions do not necessarily reflect those of my employer.  Void where prohibited. */

June 14, 2012

tolszak tolszak
Lab Rat
24 posts

You can get pointer to pushbutton in slot by using QObject::sender() method.
If you have access to pushButtonList (I suppose it’s QList) you can get button index with
pushButtonList.indexOf(sender()).

If you don’t have access to pushButtonList from slot you should check QSignalMapper as mlong suggested.

 
  ‹‹ Saving rotated QImage      property or manual variabile with setter+getter? ››

You must log in to post a reply. Not a member yet? Register here!