Best way to connect a grid of buttons to a function which takes the row and column of the button as argument
-
Suppose I have a grid of buttons. When user clicks on any of these buttons I would like to know what button the user clicked (the row and column number for the button) and use this info to do something
So I have managed to do this, but would like to see if there are other, perhaps better, ways of achieving this. Using a widget application this is what I have done so far:
Widget::Widget(QWidget *parent): QWidget(parent) { QGridLayout * grid = new QGridLayout(this); for(int i = 0; i < columns; i++) { for(int j = 0; j < rows; j++) { QPushButton * button = new QPushButton(this); grid->addWidget(button, j, i); // Set size text etc. for each button connect(button, &QPushButton::clicked, [=](){ func(i, j); // Call the function which uses i and j here }); } } } void Widget::func(int i, int j) { // Do stuff with i and j here }
-
Hi
Using a custom widget to hold the buttons and lambda to capture col, row seems
pretty fine.You could add a new signal
void ButtonPressed(int col, int row);
To "Widget"
and emit that in the lambda to allow other classes to hook into the clicked signal to do custom processing if
needed.That way you can reuse widget in other cases, where clicking on a button will do something different.
connect(button, &QPushButton::clicked, [=](){ emit ButtonPressed(i,j); });
-
Hi
Using a custom widget to hold the buttons and lambda to capture col, row seems
pretty fine.You could add a new signal
void ButtonPressed(int col, int row);
To "Widget"
and emit that in the lambda to allow other classes to hook into the clicked signal to do custom processing if
needed.That way you can reuse widget in other cases, where clicking on a button will do something different.
connect(button, &QPushButton::clicked, [=](){ emit ButtonPressed(i,j); });
-
@mrjj
If there are 100 rows and 100 columns there will be 10,000connect()
s. (And 10,000QPushButton
s; but that's not what we've been asked about.)@JonB
Hehe, right.
Well if the question was how do i have an obscene amount of pushbuttons I would have
told him to paint them and keep a list of rects and do own hittesting.
10K buttons in a layout would also be heavy when resizing :) -
@mrjj
If there are 100 rows and 100 columns there will be 10,000connect()
s. (And 10,000QPushButton
s; but that's not what we've been asked about.)