Tuesday, January 28, 2014

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 8, Running Tests

To repeat, the entire code of the example program is in this PasteBin. Copy it; save it as draggin.py; and execute it from a command line:

$ python draggin.py

Try dragging and dropping:

  • From the source onto upper part of the target
  • Onto the forbidden (lower right) quadrant of the target
  • Onto another app that accepts text drops, like a text editor
  • Onto the desktop (in Mac OS, makes a "clipping" file)
  • Onto something that doesn't accept the drop

You can also start more than one copy:

$ python draggin.py &
$ python draggin.py &

Now you have two copies. Drag and drop from the source of one onto the target of the other and note, although the drop is accepted by a Qt widget, the source doesn't get any indication of success.

Next post: hacking the QDrag class for fun (but no profit)!

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.

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 6, Drag Moves

Once dragEnterEvent() has accepted the drag, the widget begins to receive a stream of calls to its dragMoveEvent() method. You don't need to implement this if you don't care where the drop happens upon your widget's rectangle. But here is an example of one.

    def dragMoveEvent(self, event):
        pos = event.pos()
        if pos != self.move_point:
            print('drag moving at {0} {1}'.format(pos.x(), pos.y()))
            self.move_point = pos
        # To illustrate forbidden areas, we mark the lower right quadrant as
        # invalid. The lower right quadrant is the rect with top-left at w/2,
        # h/2 and with size w/2, h/2. It doesn't make sense to specify this
        # over and over, but there's no other way.
        half_width = self.width()/2
        half_height = self.height()/2
        forbidden_rect = QRect(half_width,half_height,half_width,half_height)
        #event.ignore(forbidden_rect)
        if forbidden_rect.contains(pos):
            event.ignore()
        else:
            event.accept()

The first four lines implement a debugging display. These events are continuous and rapid, even if the mouse is not moving. (That's right: dragMoveEvent is called even when the mouse does not move!) For this reason we save the last-displayed point and only display again if the mouse has actually changed position.

You could track drag move events in order to change the appearance of the widget depending on the position of the cursor, for example changing its border, or somehow highlighting a child widget when the cursor was over it.

Another use is to put restrictions on the particular part of a widget that will receive the drop. The QDragMoveEvent reference claims that if you call event.ignore(rectangle), "Moves within the rectangle are not acceptable, and will be ignored." This does not seem to be true. If you enable the example line above, event.ignore(forbidden_rect), it has no effect on the behavior of the drag and drop operation. The drop will take place in the forbidden area if that's where the mouse is released.

What does make a difference is the explicit call to event.ignore() when the drag is moving within the forbidden rectangle. If the last call to dragMoveEvent before the mouse is released ends in event.ignore(), the drop doesn't happen. The cursor wanders away and the drag ends without a drop.

If you have changed the look of the widget at the start of the drag, or during the drag moves, you would like to change it back to normal if the drag doesn't happen. That's the purpose of this code:

    def dragLeaveEvent(self, event):
        print('drag leaving')
        event.accept()

This event is delivered in two cases: one, if the user drags the cursor out of the widget's boundary; and two, if the user releases the mouse button and your dragMoveEvent ends in event.ignore(). Either counts as the drag "leaving".

Next post: dropping a load.

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 5, Detecting a Drop

Let's begin to code up a drop target widget. The code that follows contains some debugging displays. With those stripped out there isn't a lot of code.

class TargWidj(QLabel):
    '''A simple class that can detect an incoming drag
    and accept it, but only if it's a Copy of plain text.'''
    def __init__(self,text):
        super().__init__()
        self.setAcceptDrops(True)
        self.setText(text)
        self.move_point = QPoint(-1,-1)

The example drop target is another QLabel with a few extra members. The important step is setting self.setAcceptDrops(True). If this property is not set, or if it is set to False during execution, no drop-related events will be reported.

    def dragEnterEvent(self, event):
        actions = event.possibleActions()
        self.move_point = event.pos()
        msg1 = 'drag enters at {0} {1}'.format(event.pos().x(), event.pos().y())
        msg2 = 'kbd mods {0:0x} buttons {1:0x}'.format(
            int(event.keyboardModifiers()), int(event.mouseButtons()) )
        print(msg1,msg2,'offering',xlate_actions(actions))
        if event.mimeData().hasText():
            if actions & Qt.CopyAction :
                event.acceptProposedAction()
            else :
                print(' -- setting copy action')
                event.setDropAction(Qt.CopyAction)
                event.accept()

The first sign that a drag is is underway is a call to this event handler. It tells you that a dragging cursor has crossed the boundary of this widget. The first five lines above would not appear in your production code. Here they display something like

drag enters at 0 38 kbd mods 0 buttons 1 offering actions: Copy Move

The real code starts with actions = event.possibleActions(). The QDragEvent class offers a confusing array of "actions" inherited from QDropEvent.

First, event.possibleActions() returns the set of actions that were passed-in to the exec_(actions) method of the Drag object (or its equivalent in some other app!). These are the actions that the source widget is offering, or permitting, or expecting, or something like that.

Then, event.proposedAction() is one of the "possible" actions, usually just Qt.MoveAction, and I can't say why this action is singled out as a "proposal".

event.dropAction() is the action that will be performed at drop time. If you don't agree with dropAction, you can call event.setDropAction() and set a different one.

In our example, we are insisting on doing a Copy. So if Copy is offered we call event.acceptProposedAction(). If not, we set the drop action to Qt.CopyAction and call event.accept().

Why are there two different ways of accepting the event? I don't know. What I do know is that if dragEnterEvent() exits without accepting the event in one of those two ways, it has rejected the drop, and no further events related to this drop will be presented to this widget. The drop is over, as far as this widget is concerned.

In the next post we look at what happens after the drag is accepted.

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 4, Coding a Drag Source

Code for a Drag Source

The whole code for the example program is at this pastebin link. Here we will look at it in pieces. Let's implement a drag-source.

class SorcWidj(QLabel):
    '''A simple drag-source with ability
    to recognize the start of a drag motion
    and implement the drag.'''
    def __init__(self,text):
        super().__init__()
        self.setText(text)
        self.mouse_down = False # has a left-click happened yet?
        self.mouse_posn = QPoint() # if so, this was where...
        self.mouse_time = QTime() # ...and this was when.

SorcWidj is just a QLabel with a few extra features, especially three members where we note the time and place of a click. We set these fields in the following method:

    def mousePressEvent(self,event):
        if event.button() == Qt.LeftButton :
            self.mouse_down = True # we are left-clicked-upon
            self.mouse_posn = event.pos() # here and...
            self.mouse_time.start() # ...now
        event.ignore()
        super().mousePressEvent(event) # pass it on up

When the user clicks down with any mouse button on this widget, mousePressEvent is entered. For this example we are only supporting left-clicks and left-drags. So, if this is a left-click, we save the position (x and y in local coordinates) and we start a millisecond timer going. Why do we want this info? Here's why:

    def mouseMoveEvent(self,event):
        if self.mouse_down :
            # Mouse left-clicked and is now moving. Is this the start of a
            # drag? Note time since the click and approximate distance moved
            # since the click and test against the app's standard.
            t = self.mouse_time.elapsed()
            d = (event.pos() - self.mouse_posn).manhattanLength()
            if t >= QApplication.startDragTime() \
            or d >= QApplication.startDragDistance() :
                # Yes, a proper drag is indicated. Commence dragging.
                self.doSomeDraggin(Qt.CopyAction|Qt.MoveAction)
                event.accept()
                return
        # Move does not (yet) constitute a drag, ignore it.
        event.ignore()
        super().mouseMoveEvent(event)

This logic is taken straight from the Qt documentation. Whenever the mouse moves above our widget with a button down, mouseMoveEvent() is called. If our mousePressEvent decided it was valid (in this case, if it was a left-click), we note the time t and distance d since that click event.

The application has a platform-dependent standard for the amount of time and distance that the mouse should move before the motion constitutes a "drag". We test against those standards. If they are met, then we initiate a drag, accept the event, and exit. Otherwise we pass the event along. Now, let's get to the beef. How do we initiate a drag?

    def doSomeDraggin(self, actions):
        # Create the QDrag object
        dragster = QDrag(self)
        # Make a scaled pixmap of our widget to put under the cursor.
        thumb = self.grab().scaledToHeight(50)
        dragster.setPixmap(thumb)
        dragster.setHotSpot(QPoint(thumb.width()/2,thumb.height()/2))
        # Create some data to be dragged and load it in the dragster.
        md = QMimeData()
        md.setText(self.text())
        dragster.setMimeData(md)
        # Initiate the drag, which really is a form of modal dialog.
        # Result is supposed to be the action performed at the drop.
        act = dragster.exec_(actions)
        defact = dragster.defaultAction()
        # Display the results of the drag.
        targ = dragster.target() # s.b. the widget that received the drop
        src = dragster.source() # s.b. this very widget
        print('exec returns',int(act),'default',int(defact),'target',type(targ), 'source',type(src))
        return

Once you have decided that a drag is necessary, this is how you initiate it. Let's go over it in pieces.

        dragster = QDrag(self)

The QDrag object represents the drag. We will initialize it and then execute it much as we execute a modal dialog.

        thumb = self.grab().scaledToHeight(50)
        dragster.setPixmap(thumb)

The QWidget.grab() method was added in Qt5. It returns a pixmap of that widget as it looks now. Here we grab a pixmap of our own widget (we take a selfie!). And scale it to be no more than 50px high. We apply our selfie pixmap to the drag object. It will be displayed under the cursor and follow it around during the drag. The pixmap is optional; in your application you might not use it, or you might use a pixmap of something else.

        dragster.setHotSpot(QPoint(thumb.width()/2,thumb.height()/2))

Another optional step repositions the selfie thumbnail so that it is centered under the cursor. Without this, cursor will be at the top left corner of the thumbnail pixmap.

        md = QMimeData()
        md.setText(self.text())
        dragster.setMimeData(md)

This is the heart of drag initiation. You are supposed to package the data that is being dragged in the form of MIME data. MIME began as a standard for attaching arbitrary data to emails. It has been extended to allow passing data between any programs.

In principle you can package just about anything as MIME data. You load the QMimeData object with the data and set it to have the appropriate MIME type. Then you assign it to the drag object.

Why do this? Because you don't know where the drag is going. It isn't necessarily going to some other part of your app. It might be dropped anywhere, on any app, or on the desktop. By packaging the data as a MIME type, you ensure that any other application that supports MIME can accept it.

In this example, we are punting the whole issue and setting the MIME data to the current text of this QLabel. If your application has to pass something more structured than simple text, you will have to study the QMimeData reference and the Qt page on MIME data.

        act = dragster.exec_(actions)

This statement initiates the drag operation. Just as with a modal dialog, you exec_() the drag object. The argument is the set of actions you will permit the drop to perform: some OR-combination of Qt.MoveAction, Qt.CopyAction, and Qt.LinkAction. (We passed these from the mouseMoveEvent() code.)

Once the drag starts, this code is effectively suspended until the user lets go of the mouse. In Linux and Mac OS, signals continue to be processed and other threads of the app keep executing. In Windows, the whole app stops.

Eventually the user will relax her finger on the mouse and end the drag. Then, in theory, the action code that was actually performed is returned. The statements that follow in our example print out what can be learned after the drag completes: the supposed action, the default action, and the identities of the source widget (this one) and the target widget that accepted the drag.

If and only if the drop is accepted by a Qt widget in this same application, the returned action will be one of Qt.MoveAction, Qt.CopyAction, or Qt.LinkAction. And the widget returned by the target() method of the drag object will be a reference to the widget that accepted the drop.

If the drop completes in some other application, whether written in Qt or not, the returned action will be 0, and the value returned by dragster.target() will be None. Those things will also be the case if the drop simply doesn't complete, for example if the user releases the mouse over some location that doesn't accept drops.

This is a bit of a hole in the Qt drag-and-drop support. There is no standard way to tell if a drag completed successfully in another app's window, or just didn't complete.

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 3, The Drag Source

A drag source in Qt is any QWidget derivative in which:

  • MousePressEvent() is implemented to note when and where the mouse is clicked-down
  • MouseReleaseEvent() is implemented to note that the mouse is no longer clicked-down
  • MouseMoveEvent() is implemented and detects when the mouse has moved far enough, or been down long enough, to show that the user wants to begin a drag, and then...
  • It starts a drag by creating a QDrag object, loading it with data, and executing it.

One way to look at drag is that it is a peculiar kind of modal dialog, much like a QFileDialog. When the user manipulates the mouse in a certain way, you know you should initiate this "dialog". When the drag pseudo-dialog completes, you have a result that sometimes indicates what happened. Other times you are left guessing.

In the next post, we'll look at some real code to see how this is done.

Qt's Drag-and-Drop Architecture for Python and PyQt5
Pt. 2, The Drop Target

The Drop Target

A drop target in Qt is a widget (any QWidget derivative) in which:

  • The widget at some time sets self.setAcceptDrops(True)
  • The widget implements the dragEnterEvent() method
  • The widget implements the dropEvent() method

The widget may optionally implement the dragMoveEvent() and/or dragLeaveEvent() methods, but these are not usually required.

When a widget sets acceptDrops to True, it will be called at dragEnterEvent() when the mouse cursor of a user drag crosses into the widget's boundary rectangle. In this method your code inspects the purpose and content of the drag and decides if it's for you. The code can look at the modifier keys (is this an Alt/Option- or Control-drag?). It can look at the mouse buttons (left-button drag, or right-button?). It can interrogate the type and even the content of the data that would be dropped.

If dragEnterEvent() rejects the drag, nothing further happens—the mouse cursor might change to show that this drag is not allowed, or not. But no other drag-related event methods will be delivered to this widget for this drag.

If the dragEnterEvent() code indicates that the drag is acceptable, more things will happen. The cursor will move across your widget's surface, and your dragMoveEvent(), if implemented, will be called repeatedly as it does so. The cursor may wander out of your widget without dropping; if so, your dragLeaveEvent() will be called, if implemented.

Or, the user may release the mouse button over your widget. Then your dropEvent() is called. At this point you can still reject the drag; otherwise your code is supposed to take the data out of the drag and do something with it.

If this sounds complex, it is. Fortunately many Qt widgets handle drops automatically. For example, QListView and QTableView handle dragging and dropping, and it's a blessing that they do.

In the next post we'll review the design of a drag source widget.