简体   繁体   English

Qt 和 C++:多个按钮上的信号和插槽

[英]Qt and C++: Signal & Slot on multiple PushButtons

i create multiple QPushButtons in the following way:我通过以下方式创建多个 QPushButtons:

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.这工作正常,QPushButtons 显示在 GUI 上。 But how do i connect them to a clicked()-Signal and to a Slot?但是我如何将它们连接到 clicked()-Signal 和 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.您可以在_on_send_name中使用sender()来获取指向单击按钮的指针。 But sender() is not recommended.但不推荐 sender() 。 https://doc.qt.io/qt-5/qobject.html#sender https://doc.qt.io/qt-5/qobject.html#sender

I would go with the QSignalMapper for your scenario.我会为您的场景使用带有QSignalMapper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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