Qt5中一组同类型的widget connect到同一个槽函数
程序员文章站
2024-01-02 22:58:22
...
/*main.cpp*/
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
/*mainwindow.h*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QPushButton *buttons[8];
private slots:
void leds(int i);
};
#endif // MAINWINDOW_H
/*mainwindow.cpp*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
for(int i=0;i<8;i++){
buttons[i] = new QPushButton(this);
buttons[i]->resize(100,50);
buttons[i]->move(10+110*i,200);
//buttons[i]->setText("OFF","ON");
buttons[i]->show();
connect(buttons[i],&QPushButton::clicked,this,[this,i]{MainWindow::leds(i);});
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::leds(int i)
{
ui->label1->setText(QString::number(i));
}
//no more
从以下贴子学到的: