1

我想在单击时制作一个 PushButton,它的文本变为“已单击”。我试过了

connect(button1, SIGNAL(clicked()), this, SLOT(markClicked(button1))); 

在哪里this参考MainWindow

void MainWindow::markClicked(QPushButton *button) { button->setText("Clicked"); }

它似乎不起作用,因为我认为 SLOT 不能接受比 SIGNAL 更多的参数。是否有任何方法可以解决此限制?

谢谢。

4

2 回答 2

3

Qt 信号/槽机制只能将信号传递给具有相似参数的槽函数。作为一种解决方法,您应该使用QSignalMapper

QSignalMapper mapper;
...
connect(button1, SIGNAL(clicked()), &mapper, SLOT(map()));
mapper.setMapping(button1, button1); // not sure whether this is mandatory or not
...
connect(&mapper, SIGNAL(mapped(QWidget*)), this, SLOT(markClicked(QWidget*)));

和功能markClicked

void MainWindow::markClicked(QWidget *widget) {
  QPushButton *button = qobject_cast<QPushButton*>(widget);
  button->setText("Clicked");
}
于 2012-09-27T09:13:17.760 回答
1

另一种方法是使用参数的默认值,然后使用 sender() 方法:

在 MainWindow 中:
void markClicked(QPushButton *button = NULL);

然后:
connect(button1, SIGNAL(clicked()), this, SLOT(markClicked()));

和:

void MainWindow::markClicked(QPushButton *button) {
   if (button==NULL) { button = qobject_cast<QPushButton*>(sender()); }
    button->setText("Clicked");
}
于 2013-07-02T18:01:10.370 回答