How to deselect / dehighlight multiple items using QGraphicsScene::clearSelection()?

154 Views Asked by At

I have a QGraphicsScene which has 100+ items. Sometimes I need to highlight and dehighlight multiple items.

Here is the code:

HighlightObject(QEvent* event)
{
   //Finding object under cursor
   QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
   QPointF mousePoint = _view->mapToScene(mouseEvent->pos());
   QGraphicsItem* itemUnderClick = scene->itemAt(mousePoint, QTransform());
   
   QGraphicsPathItem* polylineItem = qgraphicsitem_cast<QGraphicsPathItem*>(itemUnderClick);
    if (polylineItem ) {
        //polylineItem ->setFlag(QGraphicsItem::ItemIsSelectable);//I have set this flag while drawing polyline.
        polylineItem ->setSelected(true);
        QPen mPen(Qt::SolidLine);
        mPen.setWidth(1);
        polylineItem ->setPen(mPen);
      }
}     
 

My scene has 1 button which refreshes the scene. (which dehighlight all the items in the scene)

 Refresh()
   {
      foreach (QGraphicsItem* currentItem, scene->items()) 
     {
       myPoly* pItem = qgraphicsitem_cast<myPoly*>(currentItem);
       if (pItem)  
       {
           pItem->setSelected(false);
           pItem->setPen(QPen(QColor("red")); // original color of polyline is red.
       }
    }

Above code works fine. But my scene has many elements so this Refresh() becomes costly.
So in Refresh() I tried :

foreach (QGraphicsItem* currentItem, scene->selectedItems())

But above does not work for multiple selection. It means if I have selected 2 itms from the scene, and now I want to dehighlight both of them, then it always dehighlight 1 item.
I tried to print the value of

scene->selectedItems().size() => 1

So I want to :

  1. Dehighlight multiple object.
  2. To dehighlight 1 object, I do not want to iterate over all scene.

I got some hint:

If you want to deselect / dehighlight  all selected items quickly 
then try to use QGraphicsScene::clearselection() 

How to use QGraphicsScene::clearselection() here ?

0

There are 0 best solutions below