Search code examples
c++qtsignals-slotsqpushbutton

Qt and C++: Signal & Slot on multiple PushButtons


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


Solution

  • 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