简体   繁体   中英

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

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

I would go with the QSignalMapper for your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM