Search code examples
c++qtqgraphicsview

How does one retrieve selected area from QGraphicsView?


I need my QGraphicsView to react on user selection - that is, change display when user selects area inside it. How can i do that?

As far as i can tell, selection in Qt Graphics framework normaly works through selection of items. I haven't found any methods/properties that touch on selected area, save for QGraphicsVliew::rubberBandSelectionMode, which does not help.


Solution

  • After some going through documentation, i found different solution.

    In QGraphicsView there is a rubberbandChanged signal, that contained just the information i wanted to use. So, i handled it in a slot, resulting in the handler of following form:

    void 
    MyImplementation::rubberBandChangedHandler(QRect rubberBandRect, QPointF fromScenePoint, QPointF toScenePoint)
    {
        // in default mode, ignore this
        if(m_mode != MODE_RUBBERBANDZOOM)
            return;
    
        if(rubberBandRect.isNull())
        {
            // selection has ended
            // zoom onto it!
            auto sceneRect = mapToScene(m_prevRubberband).boundingRect();
            float w = (float)width() / (float)sceneRect.width();
            float h = (float)height() / (float)sceneRect.height();
    
            setImageScale(qMin(w, h) * 100);
            // ensure it is visible
            ensureVisible(sceneRect, 0, 0);
    
            positionText();
        }
    
        m_prevRubberband = rubberBandRect;
    }
    

    To clarify: my implementation zooms on selected area. To that effect class contains QRect called m_prevRubberband. When user stop selection with rubberband, parameter rubberBandRect is null, and saved value of rectangle can be used.

    On related note, to process mouse events without interfering with rubber band handling, m_prevRubberband can be used as a flag (by checking it on being null). However, if mouseReleaseEvent is handled, check must be performed before calling default event handler, because it will set m_prevRubberband to null rectangle.