Question

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.

Was it helpful?

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.

OTHER TIPS

You can use qgraphicsscenemouseevent.

On MousePress save the current position and on MouseRelease you can compute a bounding rect using the current position and the MousePress position.

This gives you the selected area. If you need custom shapes you could track the mouse movement (MouseMove) to get the shape.

An Example that uses qgraphicsscenemouseevent can be found here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top