0

I would like to set the font color and the background color if I click on a button.

I just added these two functions to the mainwindow.h file

public:
    void createGrid();

private slots:
    void clickCell(int row, int col);

mainwindow.cpp

QVector<QVector<QPushButton*>> buttons(10);

void MainWindow::createGrid() {
    QFrame *frame = new QFrame(this);
    QGridLayout *layout = new QGridLayout(frame);

    layout->setMargin(0);
    layout->setSpacing(0);

    for(int i = 0; i < 10; ++i){
        buttons[i].resize(10);

        for(int j = 0; j < 10; ++j){
            QPushButton *button = new QPushButton("0");

            button->setMinimumSize(50,50);
            button->setMaximumSize(50,50);

            connect(button,SIGNAL(released()),this,SLOT(clickCell(i,j)));

            layout->addWidget(button,i,j);

            buttons[i][j] = button;
        }

    }

    setCentralWidget(frame);
}

void MainWindow::clickCell(int row, int col) {
    buttons[row][col]->setStyleSheet("background-color: grey; color: red");
}

When I run my code I am getting the following outputs about 100 times:

QObject::connect: No such slot MainWindow::clickCell(i,j) in ..\untitled\mainwindow.cpp:41
QObject::connect:  (receiver name: 'MainWindow')
  • Getting the sender would probably be the preferable solution ( https://stackoverflow.com/a/35435449/2991525 ) – fabian Jun 18 '21 at 16:29
  • Use the new signal/slot syntax to call a `lambda` as a slot with `i` and `j` captured in the `lambda`. – G.M. Jun 18 '21 at 16:32

1 Answers1

1

As per the comment: use the new signal/slot syntax to invoke a lambda as the slot. So your connect call should be something like (untested)...

connect(button, &QPushButton::released, this,
        [=, this]
        {
            clickCell(i, j);
        });
G.M.
  • 12,232
  • 2
  • 15
  • 18