我有QListQPushButtonQSignalMapper来识别按下了哪个按钮。
所以我做了类似的事情(我的项目很大,所以我只删了问题所需要的界线)

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)指向不存在的按钮。

最佳答案

从理论上讲,您可以保持指向信号映射器的指针,并在删除后重新映射索引。

void myclass::deleteButton(int i){
    delete (Buttons.takeAt(i));
    for(int i = 0; i < Buttons.size(); ++i) {
        ButtonsMapper->setMapping(Buttons[i], i);
    }
}

09-25 22:07