如何使用来自 Qt PushButton 的单击信号传递值?

Jul*_*ien 4 c++ qt slot

我有 n 个按钮最初都标记为“0”。当程序运行时,这些标签或值将更改为不同的整数,例如在某些时候我可能有:'7'、'0'、'2'、...

我有一个将 int 作为参数的函数(或插槽):

void do_stuff(int i);
Run Code Online (Sandbox Code Playgroud)

我想在按下“x”时调用 do_stuff(x)。即:当按下任何按钮时,使用该按钮的值调用 do_stuff。我怎样才能做到这一点?到目前为止,我有类似的东西:

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])));
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*r V 5

我会将其简化为通常用于解决此类任务的内容:

public slots:
   void do_stuff(); // must be slot
Run Code Online (Sandbox Code Playgroud)

并且连接应该像

connect(button, SIGNAL(clicked()), SLOT(do_stuff()));
Run Code Online (Sandbox Code Playgroud)

然后 MyClass::do_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
     }
 }
Run Code Online (Sandbox Code Playgroud)