0

i create multiple QPushButtons in the following way:

QList<QByteArray> pBList;
    pBList= rec_data.split(',');

    for (int i = 1; i < pBList.size() -1; i++){             
        QPushButton *newpB = new QPushButton(ui->verticalLayoutWidget);
        newpB->setText(pBList[i]);
        ui->verticalLayoutWidget->layout()->addWidget(newpB);
    }

This works fine and the QPushButtons are shown on the GUI. But how do i connect them to a clicked()-Signal and to a Slot? I tried it this way, but this dosen't work...

QObject::connect(ui->verticalLayoutWidget->layout()->itemAt(1)->widget(), SIGNAL(clicked()),this, SLOT(_on_send_name()));

Thanks for the help

Amy15Fee
  • 35
  • 5
  • Why does it not work? Why not connect the item directly, when you create it? – RoQuOTriX Jul 08 '20 at 05:45
  • 3
    Your exposed code looks not that bad. Please, clarify _this dosen't work..._ Compiler error? Signals not working? Did you make `_on_send_name` a slot? Btw. with the new Qt5 signal/slot concept you get compile time checks (in opposition to runtime checks), and you don't need signal handlers to remarked as slots explicitly. (Any function or member function may be used, lambda functions included.) FYI: [New Signal Slot Syntax](https://wiki.qt.io/New_Signal_Slot_Syntax) – Scheff's Cat Jul 08 '20 at 05:45
  • @Scheff I did made the function _on_send_name a slot but like you said the signal is not working. When i click on the PushButton it won't go into the function it goes directly to the next line – Amy15Fee Jul 08 '20 at 06:27
  • _When i click on the PushButton it won't go into the function it goes directly to the next line_ Sorry, I don't understand this. What next line? Signal handlers are called out of event handlers which are called out of the event loop (in `QApplication`). Just FYI: [SO: How to call defined slots from keypress event in qt / How to connect keypressed event with QPushbutton on gui?](https://stackoverflow.com/a/61381278/7478597) an example for signal handlers with lambda functions. – Scheff's Cat Jul 08 '20 at 06:38
  • Refer [How to make slot for multiple QPushButtons?](https://stackoverflow.com/a/71755699/10060901) – Vinu Raja Kumar C Apr 05 '22 at 17:05

2 Answers2

1
QList<QByteArray> pBList;
    pBList= rec_data.split(',');

    for (int i = 1; i < pBList.size() -1; i++){             
        QPushButton *newpB = new QPushButton(ui->verticalLayoutWidget);
        newpB->setText(pBList[i]);
        ui->verticalLayoutWidget->layout()->addWidget(newpB);
        //This will CONNECT all buttons to a single slot
        connect (newpB,&QPushButton::clicked,this,&YOUR_CLASS_NAME::_on_send_name);
    }

You can use sender() inside _on_send_name to get a pointer to the clicked button. But sender() is not recommended. https://doc.qt.io/qt-5/qobject.html#sender

smacker
  • 151
  • 6
0

I would go with the QSignalMapper for your scenario.

rbaleksandar
  • 8,713
  • 7
  • 76
  • 161