Amy15Fee
Amy15Fee

Reputation: 35

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

Upvotes: 0

Views: 503

Answers (2)

rbaleksandar
rbaleksandar

Reputation: 9701

I would go with the QSignalMapper for your scenario.

Upvotes: 0

smacker
smacker

Reputation: 151

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

Upvotes: 1

Related Questions