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

我的梦境 提交于 2019-12-23 12:35:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!