4

我有QList' QPushButtons 和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)指向不存在按钮。

4

3 回答 3

1

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

void myclass::deleteButton(int i){
    delete (Buttons.takeAt(i));
    for(int i = 0; i < Buttons.size(); ++i) {
        ButtonsMapper->setMapping(Buttons[i], i);
    }
}
于 2012-09-06T17:23:07.397 回答
0

我建议您对代码进行一些修改:

QMap<QPushButton*,int> Buttons;
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.insert (new QPushButton(tr("0")),0);//first button 
QPushButton * pb1 = Buttons.last();//pointer to the last button
connect(pb1, SIGNAL(clicked()), ButtonsMapper, SLOT(map()));
ButtonsMapper->setMapping(pb1,0);

Buttons.insert (new QPushButton(tr("1")),1);//second button 
QPushButton * pb2 = Buttons.last();//pointer to the last button
connect(pb2, SIGNAL(clicked()), ButtonsMapper, SLOT(map()));
ButtonsMapper->setMapping(pb2,1);

void myclass::deleteButton(int i){
    if (Buttons.contains(i))
    delete (Buttons[i]);  
}
于 2012-09-06T14:24:17.987 回答
0

除了将 QPushButton 映射到 index( int) 之外,您还可以将其映射到QWidget *.

- ButtonsMapper->setMapping(pb1,0);
+ ButtonsMapper->setMapping(pb1, pb1);

然后插槽也会改变

void myclass::deleteButton(QWidget * widget){
    Buttons.removeOne(widget);
    delete widget;  
}
于 2012-09-06T19:38:41.403 回答