Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a value with a clicked signal from a Qt PushButton? [duplicate]

Tags:

c++

qt

slot

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])));
}
like image 544
Julien Avatar asked Sep 22 '15 00:09

Julien


1 Answers

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
     }
 }
like image 76
Alexander V Avatar answered Sep 29 '22 10:09

Alexander V