Monday, January 27, 2014

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 7, Drop the load

All right, let's drop that load!

    def dropEvent(self, event):
        msg = 'dropping at {0} {1}'.format(event.pos().x(), event.pos().y())
        actions = event.dropAction()
        print(msg, xlate_actions(actions))
        if actions & Qt.CopyAction :
            event.acceptProposedAction()
        else :
            print(' -- setting copy action!')
            event.setDropAction(Qt.CopyAction)
        self.setText( event.mimeData().text() )
        event.accept()

If dragMoveEvent() is not implemented, or it executes event.accept() just before the mouse button is released, the drop proceeds by calling your dropEvent() method.

The first three lines above just print debugging info; they would not be in production code.

The next lines make sure that we will do a copy and that the drag source widget will know this was the case. The event.dropaction() value is the value that will be returned by the drag object's exec_() method, so we force it to Copy if it isn't already Copy.

Of course, that is only useful if indeed the drag was started by a Qt drag source like the one we coded at a few posts back; and if that drag source is in this same Qt app. If the drag was begun in another Qt app, nothing is reported back; and if it began in a non-Qt app, who knows what it expects?

Finally we take the data from the MIME object and use it. In this pathetically simple example that means setting it as this QLabel's text. Then we accept the event, and this ends the drag successfully.

It is possible to reject the drop even at this late point. Your code could examine the MIME data and decide it is not acceptable, or perhaps some resource it needs is not available just now. If the drop can't be accepted for any reason, just call event.ignore() and exit. The drop fails.

No comments: