我有QList
' QPushButton
s 和QSignalMapper
识别哪个按钮被按下。所以我做了类似的事情(我的项目非常大,所以我只剪掉了问题所需的线条)
QList<QPushButton*> Buttons;
QList <QLabel*> LabelList1;
QList <QLabel*> LabelList2;
QList <QLabel*> LabelList3;
QList <QLabel*> LabelList4;
QSignalMapper *ButtonsMapper;
ButtonsMapper= new QSignalMapper(this);
connect(ButtonsMapper, SIGNAL(mapped(int)),this,SIGNAL(ButtonsClicked(int)));
connect(this, SIGNAL(ButtonsClicked(int)),this,SLOT(deleteButton(int)));
Buttons.append(new QPushButton(tr("0")));//first button
LabelList1.append(new QLabel(tr("0")));
LabelList2.append(new QLabel(tr("0")));
LabelList3.append(new QLabel(tr("0")));
LabelList4.append(new QLabel(tr("0")));
QPushButton * pb1 = Buttons.last();//pointer to the last button
connect(pb1, SIGNAL(clicked()), ButtonsMapper, SLOT(map()));
ButtonsMapper->setMapping(pb1,0);
Buttons.append(new QPushButton(tr("1")));//second button
LabelList1.append(new QLabel(tr("1")));
LabelList2.append(new QLabel(tr("1")));
LabelList3.append(new QLabel(tr("1")));
LabelList4.append(new QLabel(tr("1")));
QPushButton * pb2 = Buttons.last();//pointer to the last button
connect(pb2, SIGNAL(clicked()), ButtonsMapper, SLOT(map()));
ButtonsMapper->setMapping(pb2,1);
并且按下了deleteButton
应该删除按钮的功能。如果我做这样的事情
void myclass::deleteButton(int i){
delete (Buttons.takeAt(i));
delete ( LabelList1.takeAt(i));
delete ( LabelList2.takeAt(i));
delete( LabelList3.takeAt(i));
delete( LabelList4.takeAt(i));
}
该功能可能会导致index out of range
错误,如果我删除第一个按钮,然后按第二个按钮,则功能Buttons.takeAt(i)
指向不存在按钮。