1

In a scene with multiple groups, how can I delete the selected item group? When I try to delete the group, it only deletes the last created group.

#include "graphicscene.h"    

QGraphicsItemGroup *mpGroup ;

void GraphicScene::keyReleaseEvent(QKeyEvent * keyEvent)
{
    if( keyEvent->key() == Qt::Key_F1) {
        qDebug() << "group created";
        mpGroup = createItemGroup(selectedItems());
        mpGroup->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
        qDebug() << "Group Address "<< mpGroup ;
    } else if( keyEvent->key() == Qt::Key_F2)  { 
        qDebug() << "Group Before delete selected item"<< selectedItems() ;  
        if(mpGroup != NULL) {  
            destroyItemGroup(mpGroup);
            qDebug() << "Group Deleted "<< mpGroup ;
        }
    } 
}

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Sagar A W
  • 338
  • 1
  • 12

1 Answers1

1

A possible solution is to use type() to verify that it is a QGraphicsItemGroup.

void GraphicScene::keyReleaseEvent(QKeyEvent * keyEvent){      
    if( keyEvent->key() == Qt::Key_F1)
    {
        qDebug() << "group created";
        QGraphicsItemGroup *group = createItemGroup(selectedItems());
        group->setFlags(QGraphicsItem::ItemIsSelectable | 
                 QGraphicsItem::ItemIsMovable);
        qDebug() << "Group Address "<< group ;
    }
    else if( keyEvent->key() == Qt::Key_F2)  
    { 
        qDebug() << "Group Before delete selected item"<< selectedItems() ; 
        for(QGraphicsItem *item: selectedItems()){
            if(item->type() == QGraphicsItemGroup::Type)    
            {     
                 QGraphicsItemGroup *group = qgraphicsitem_cast<QGraphicsItemGroup *>(item);
                 destroyItemGroup(group);
                 qDebug() << "Group Deleted "<< group ;
            }
        }
    } 
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241