In ScrollHandDrag mode of QGraphicsView, How to st

2019-06-20 14:26发布

问题:

I have multiple QGraphicsItems in scene spread across different parts of scene. In application there are different modes in one of mode user can scroll the scene (palm drag mode). To achieve scrolling over scene I set dragMode of QGraphicsView to ScrollHandDrag.

But the problem is when user try to scroll over scene by dragging (MousePress and MouseMove) on any of QGraphicsItem instead of scrolling scene it moves QGraphicsItem.

How can I stop movement of QGraphicsItem and scroll the scene, but I still want to select QGraphicsItems?

Any Solution or any pointers will help.

NOTE : There are very large number of QGraphicsItems and are of various type. So It is not possible to install event filter on QGraphicsItems.

回答1:

Instead of modifying the item flags I set the whole view not interactive while in ScrollHandDrag Mode. The problem is, that you need to have an additional interaction type (i.e. Control Key, Other Mouse Button etc) to enable it.

setDragMode(ScrollHandDrag);
setInteractive(false);


回答2:

Solved !!

Please refer Question I asked on Qt Forum : Click Here

Solution/Example:

void YourQGraphicsView::mousePressEvent( QMouseEvent* aEvent )
{
    if ( aEvent->modifiers() == Qt::CTRL ) // or scroll hand drag mode has been set - whatever condition you like :)
    {
        QGraphicsItem* pItemUnderMouse = itemAt( aEvent->pos() );
        if ( pItemUnderMouse )
        {
            // Track which of these two flags where enabled.
            bool bHadMovableFlagSet = false;
            bool bHadSelectableFlagSet = false;
            if ( pItemUnderMouse->flags() & QGraphicsItem::ItemIsMovable )
            {
                bHadMovableFlagSet = true;
                pItemUnderMouse->setFlag( QGraphicsItem::ItemIsMovable, false );
            }
            if ( pItemUnderMouse->flags() & QGraphicsItem::ItemIsSelectable )
            {
                bHadSelectableFlagSet = true;
                pItemUnderMouse->setFlag( QGraphicsItem::ItemIsSelectable, false );
            }

            // Call the base - the objects can't be selected or moved by this click because the flags have been un-set.
            QGraphicsView::mousePressEvent( aEvent );

            // Restore the flags.
            if ( bHadMovableFlagSet )
            {
                pItemUnderMouse->setFlag( QGraphicsItem::ItemIsMovable, true );
            }
            if ( bHadSelectableFlagSet )
            {
                pItemUnderMouse->setFlag( QGraphicsItem::ItemIsSelectable, true );
            }
            return;
        }
    }


    // --- I think This is not required here
    // --- as this will move and selects the item which we are trying to avoid.
    //QGraphicsView::mousePressEvent( aEvent );

}