C++ (Qt)#include <QApplication>#include <QLabel>#include <QLayout>#include <QPushButton> class Widget: public QWidget { QLabel *label;public: Widget() { label = new QLabel("nothing"); auto layout = new QVBoxLayout(); layout->addWidget(label); const int n = 5; for (int i = 0; i < n; ++i) { auto button = new QPushButton(QString::number(i)); layout->addWidget(button); connect(button, &QPushButton::clicked, [=] (bool) { setText(QString("button %1 clicked").arg(i)); }); } setLayout(layout); } void setText(const QString &text) { label->setText(text); }}; int main(int argc, char *argv[]){ QApplication app(argc, argv); Widget widget; widget.show(); return app.exec();}
C++ (Qt)#include <QApplication>#include <QLabel>#include <QLayout>#include <QPushButton> #include <functional> int main(int argc, char *argv[]){ QApplication app(argc, argv); auto label = new QLabel("nothing"); auto layout = new QVBoxLayout(); layout->addWidget(label); const int n = 10; for (int i = 0; i < n; ++i) { auto button = new QPushButton(QString::number(i)); layout->addWidget(button); auto text = QString("button %1 clicked").arg(i); QObject::connect(button, &QPushButton::clicked, std::bind(&QLabel::setText, label, text)); } QWidget widget; widget.setLayout(layout); widget.show(); return app.exec();}