Qt使用函数连接多个信号和插槽

Qt connect multiple signal with slot using function

我想设置点击按钮时的字体颜色和背景颜色。

我刚刚将这两个函数添加到 mainwindow.h 文件

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");
}

当我 运行 我的代码时,我得到以下输出大约 100 次:

QObject::connect: No such slot MainWindow::clickCell(i,j) in ..\untitled\mainwindow.cpp:41
QObject::connect:  (receiver name: 'MainWindow')

根据评论:使用新的 signal/slot 语法调用 lambda 作为插槽。所以你的 connect 电话应该是这样的(未经测试)...

connect(button, &QPushButton::released, this,
        [=, this]
        {
            clickCell(i, j);
        });