问题
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])));
}
回答1:
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
}
}
来源:https://stackoverflow.com/questions/32706410/how-to-pass-a-value-with-a-clicked-signal-from-a-qt-pushbutton