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;
}
}
兩個部分看起來OK。如果設計好壞取決於最終要求 – eferion 2014-09-10 15:47:19
謝謝@eferion :)我會繼續前進。 – Rachael 2014-09-10 15:49:14