Search code examples
qtqpushbuttonqt-signals

How to get the text of dynamically added QPushButton when clicked


I have added a set of pushbuttons inside a QScrollarea dynamically , but I want to get the text of that particular button either by click or touch.

button = new QPushButton("someText");
button->setParent(ui->scrollArea);
button->setCheckable(true);
button->show();

I used button->text(); and button->currentText();. But it gives the text of the last added pushbutton, but not the clicked button.


Solution

  • G.M. said:

    [...] use a lambda as the slot when you call connect.

    One way to get any QPushButton's text when clicked, is to connect its clicked() slot to a lambda that stores button text, in a QString for example:

    QPushButton button = new QPushButton();
    button->setText("some text");
    QString buttonText;
    
    QObject::connect(button,&QPushButton::clicked,[=](){ buttonText = button->text(); qDebug()<<buttonText; });
    
    

    qDebug is just there to confirm that the button's text has been stored in buttonText, for debugging purposes.