使用 Lambda 表达式捕获按钮对象
通过 Lambda 表达式连接信号和槽时,可以直接捕获按钮对象。
#include <QApplication>
#include <QPushButton>
#include <QDebug>class MyWidget : public QWidget {Q_OBJECT
public:MyWidget() {QPushButton *button1 = new QPushButton("Button 1", this);QPushButton *button2 = new QPushButton("Button 2", this);connect(button1, &QPushButton::clicked, [this, button1]() {onButtonClicked(button1);});connect(button2, &QPushButton::clicked, [this, button2]() {onButtonClicked(button2);});button1->move(50, 50);button2->move(50, 100);}private:void onButtonClicked(QPushButton *button) {qDebug() << "Button clicked:" << button->text();}
};int main(int argc, char *argv[]) {QApplication app(argc, argv);MyWidget widget;widget.resize(200, 200);widget.show();return app.exec();
}
jzz,1=
from deepseek