2014-04-10 6 views
2

아래 코드를 사용하여 장면 바깥 쪽을 떠난 후에 항목을 제거 할 수 있다고 생각했지만 그렇지 않습니다. 다른 구현을 시도한 후에 다른 접근법을 시도해야한다고 생각합니다. 일부 QGraphicsItems는 실제로 boundingRect 외부에서 시작하므로 특정 좌표 점을 통과 한 후 GraphicsItems를 제거하고 삭제하는 방법이 있는지 궁금합니다.boundingRect를 종료 한 후 QGraphicsitems를 제거하는 방법

void Scene::advance() 
{ 
     QList <QGraphicsItem *> itemsToRemove; 
     foreach(QGraphicsItem * item, this->items()) 
     { 

      if(!this->sceneRect().intersects(item->boundingRect())) 
      { 
       // The item is no longer in the scene rect, get ready to delete it 
       itemsToRemove.append(item); 
      }     

     } 

     foreach(QGraphicsItem * item, itemsToRemove) 
     { 
      this->removeItem(item); 
      delete(item); 
     }  

     QGraphicsScene::advance(); 
} 

답변

1

문제는이 라인에있다 : -

if(!this->sceneRect().intersects(item->boundingRect())) 

이것은 장면 좌표에있는 장면의 rect와 항목의 로컬 좌표계에있는 항목의 경계 rect를 비교합니다.

동일한 좌표계 내에서 비교할 수 있도록 그 중 하나를 변환해야합니다.

QRectF itemSceneBoundingRect = item->mapRectToScene(item->boundingRect()); 
if(!this->sceneRect().intersects(itemSceneBoundingRect) 
{ 
     // remove the item. 
} 
1

각 항목의 상태를 저장하고 상태를 추적 할 수 있습니다. 당신은 같은 두 QVectors 자신의 상태에 따라 항목을 가질 수 있습니다

QVector<QGraphicsItem *> items; 
QVector<bool> itemIsInBoundingRect; // whether item is boundingrect or not 

그리고 자신의 상태를 업데이트하고 상태 변경을 추적 :

void Scene::advance() 
{ 
     for(int i=0;i<items.count();i++) 
     { 

      if(this->sceneRect().intersects(items[i]->boundingRect())) 
      { 
       // The item is in scene rect 
       itemIsInBoundingRect[i] = true; 
      } 
      else // The item is in not in scene rect 
      { 
       if(itemIsInBoundingRect[i]) // track state change 
       { 
        this->removeItem(items[i]); 
        delete(items[i]); 
        items.remove(i); 
        itemIsInBoundingRect.remove(i); 
       } 

      }     

     } 

     QGraphicsScene::advance(); 
} 
관련 문제