was successfully added to your cart.
Uncategorized

Drag & Drop in PyQt QGraphicsView

By October 29, 2016 No Comments

After some tests, I have noticed that to add Drag & Drop behaviour in a QGraphicsView you must to override dragMoveEvent.

The next snippet is a simple example class that shows a QGraphicsView that accepts drag and drop actions.

from Qt import QtCore as qc
from Qt import QtGui as qg
from Qt import QtWidgets as qw

class ControlView(qw.QGraphicsView):
    
    """
    Base class to create the control view
    """
    
    def __init__(self, scene, parent):
        
        """
        @param scene: QGraphicsScene that defines the scene we want to visualize
        @param parent: QWidget parent
        """
        super(ControlView, self).__init__(parent)
        
        self.setObjectName('ControlView')
        self.setScene(scene)
        self.setRenderHint(qg.QPainter.Antialiasing)
        self.setTransformationAnchor(qw.QGraphicsView.AnchorUnderMouse)
        self.setViewportUpdateMode(qw.QGraphicsView.SmartViewportUpdate)
        
        self.setAcceptDrops(True)
        self.setDragMode(qw.QGraphicsView.ScrollHandDrag)
        
        self.dragOver = False
        
    def dragMoveEvent(self, event):
        pass
        
    def dragEnterEvent(self, event):   
        if event.mimeData().hasText():
            event.setAccepted(True)
            self.dragOver = True
            self.update()
            
    def dropEvent(self, event):
        pos = event.pos()
        event.acceptProposedAction()