【发布时间】:2021-09-03 09:16:30
【问题描述】:
如果我点击一个按钮,我想设置字体颜色和背景颜色。
我刚刚将这两个函数添加到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')
【问题讨论】:
-
获取发件人可能是更好的解决方案(stackoverflow.com/a/35435449/2991525)
-
使用新的信号/槽语法调用
lambda作为槽,在lambda中捕获i和j。
标签: c++ qt signals-slots