I have a QList from QPushButton and QSignalMapper to find out which button is clicked. So I did something like this (my project is very large, so I cut only the lines needed to answer the question)
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);
and the deleteButton function was pressed, which was supposed to delete the button. If I do something like this
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)); }
this function can lead to an index out of range error if I delete the first button and then press the second button, the Buttons.takeAt(i) button indicates the absence of an existing button.
source share