我有一个QList
的QPushButton
和一个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));
}
如果我删除第一个按钮,然后按下第二个按钮,那么该函数可能会导致索引超出范围
错误,因为函数Buttons.takeAt(i)
指向不存在的按钮。