如何删除选定的图形项目组?

时间:2018-07-19 07:13:54

标签: c++ qt qt5 qgraphicsscene qgraphicsitem

在具有多个组的场景中,如何删除所选的项目组? 当我尝试删除组时,它只会删除最后创建的组。

#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

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是使用type()来验证它是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 ;
            }
        }
    } 
}