In a GUI application, I have quite a few pushbuttons that are being used. These pushbuttons are labelled as pbxx
where xx
is the row and column number of the pushbutton in a grid layout. When a pushbutton is pressed, it needs to be highlighted. Today I read about lambda functions Brian Poteat & Kuba Ober and thought I would try to implement this in my code.
In my GuiDisplay class (a class that inherits QMainWindow), I have a function called:
make_connections();
which would make all my pushbutton connections (all signals are connected to a single slot on_pushbutton_clicked()
. I added the code here:
The GuiDisplay Class
class GuiDisplay : public QMainWindow
{
Q_OBJECT
public:
explicit GuiDisplay(QWidget *parent = 0);
~GuiDisplay();
... Some more public functions ...
/**
* @brief Connects all custom signals and slots.
*/
void make_connections();
/**
* @brief Will highlight the provided pushbutton with provided rgb colour
*/
void highlight_pushbutton(QPushButton &pb, const int rgb[]);
private slots:
void on_pushbutton_clicked(const QString& label);
private:
Ui::GuiDisplay *ui;
};
The make_connections function of the GuiDisplay Class
void GuiDisplay::make_connections()
{
// Loop through all the pushbuttons and connect clicked signal to clicked slot
QString pb_label = "";
for(int i = 0; i < 8; ++i)
{
for(int j = 0; j < 8; ++j)
{
// Find the pushbutton
pb_label = "pb" + QString::number(i) + QString::number(j);
QPushButton* pb_ptr = this->findChild<QPushButton*>(pb_label);
//connect(pb_ptr, SIGNAL(clicked()), this, SLOT(on_pushbutton_clicked()));
connect(pb_ptr, &QPushButton::clicked, [this]{on_pushbutton_clicked(pb_label);});
}
}
}
The problem comes up when I make the connection
connect(pb_ptr, &QPushButton::clicked, [this]{on_pushbutton_clicked(pb_label);});
the build gives me the following error
'pb_label' is not captured
so I thought ok, well then it wouldn't seem wrong to do the following instead:
connect(pb_ptr, &QPushButton::clicked, [this, &pb_label]{on_pushbutton_clicked(pb_label);});
The error at build time fell away, however my GUI application unexpectedly crashes whenever this code is executed. Not sure why. Any help here?