5

I have n buttons initially all labeled '0'. These labels, or values, will change to different integers when the program runs, for example at some point I may have: '7', '0', '2', ...

I have a function (or slot) that takes an int as argument:

void do_stuff(int i);

I want to call do_stuff(x) when 'x' is pressed. That is: when whatever button is pressed, call do_stuff with that button's value. How can I do that? So far I have something like:

std::vector values; // keeps track of the button values
for (int i = 0; i < n; i++){
    values.push_back(0);
    QPushButton* button = new QPushButton("0");
    layout->addWidget(button);
    // next line is nonsense but gives an idea of what I want to do:
    connect(button, SIGNAL(clicked()), SLOT(do_stuff(values[i])));
}
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Julien
  • 13,986
  • 5
  • 29
  • 53

1 Answers1

5

I would simplify that to what usually used for solving such task:

public slots:
   void do_stuff(); // must be slot

and the connect should be like

connect(button, SIGNAL(clicked()), SLOT(do_stuff()));

then MyClass::do_stuff does stuff:

 void MyClass::do_stuff()
 {
     QPushButton* pButton = qobject_cast<QPushButton*>(sender());
     if (pButton) // this is the type we expect
     {
         QString buttonText = pButton->text();
         // recognize buttonText here
     }
 }
Alexander V
  • 8,351
  • 4
  • 38
  • 47
  • That looks like another good way, although in my case crayzeewulf's mapping suggestion seems a better fit (what I'm doing in real is more complex than the toy example in my post). But since this answers the actual posted question, I'll accept it! – Julien Sep 22 '15 at 02:15
  • @JulienBernu, you can inherit from QPushButton and then cast sender() to that new type and read whatever you need from it. Make sure to set all the data with inherited QPushButton. – Alexander V Sep 22 '15 at 02:24