Search code examples
qtmouseeventqgraphicsitem

trigger mouseMoveEvent of several QGraphicsItem at the same time


When I select several QGraphicsItem (with Ctrl key) I can move them together, but the mouseMoveEvent is triggered only for the item that actually receives the event. Is there a way to make every selected items receive the event ? I can't find it in Qt's doc.

Could I group selected items together and handle it within QGraphicsView's mouseMoveEvent ?

Thanks a lot for any help :)


Solution

  • No there is no default way to do what you want as far as I know. Something you could do is the following:

    • Subclass QGraphicsScene and implement the mouseMoveEvent
    • In the mouse move event check if there is an item at the event position using the itemAt function
    • If there is an item and it is selected (isSelected), get all selected items of the scene.
    • For all selected items call the same function you would call.

    Sample code follows:

    void mouseMoveEvent(QGraphicsSceneMouseEvent * mouseEvent) 
    {
        QPointF mousePosition = mouseEvent->scenePos();
        QGraphicsItem* pItem = itemAt(mousePosition.x(), mousePosition.y());
        if (pItem == NULL)
        {
            QGraphicsScene::mouseMoveEvent(mouseEvent);
            return;
        }
    
        if (pItem->isSelected() == false)  
        {
            QGraphicsScene::mouseMoveEvent(mouseEvent);
            return;
        }
    
        // Get all selected items
        QList<QGraphicsItem *> items = selectedItems();
    
        for (unsinged i=0; i<items.count(); i++)
            // Do what you want to do when a mouse move over a selected item.
            items[i]->doSomething(); 
    
        QGraphicsScene::mouseMoveEvent(mouseEvent);  
    }