A部分看起来很正常。
B部分看起来也很正常,但是如果你想知道哪个小部件发出信号,你应该使用这样的东西(在你的情况下,你的插槽对每个小部件都做同样的事情)
的使用QSignalMapper
signalMapper = new QSignalMapper(this);
for (int i = 0; i < 3; ++i)
{
QPushButton *button = new QPushButton(QString::number(i),this);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
button->move(i*10,i*10);//doesn't matter
signalMapper->setMapping(button, QString::number(i));
}
connect(signalMapper, SIGNAL(mapped(const QString &)),
this, SLOT(clicked(const QString &)));
//...
void MainWindow::clicked(const QString & text)
{
QMessageBox::information(this, "TEST", text, QMessageBox::Ok);
}
或使用sender()
for (int i = 0; i < 3; ++i)
{
QPushButton *button = new QPushButton(QString::number(i),this);
button->setObjectName(QString::number(i));//important
connect(button, SIGNAL(clicked()), this, SLOT(clicked()));
button->move(i*10,i*10);
}
void MainWindow::clicked()
{
switch( sender()->objectName().toInt())
{
case 0:
QMessageBox::information(this, "TEST", "0", QMessageBox::Ok);//do something specific to 0 widget
break;
case 1:
QMessageBox::information(this, "TEST", "1", QMessageBox::Ok);//do something specific to 1 widget
break;
case 2:
QMessageBox::information(this, "TEST", "2", QMessageBox::Ok);//and so on
break;
}
}