Drag & Drop in Qt Applications

Last edited on

Overview

Usually one would use these functions to perform drag & drop in Qt applications:

However, the actions possible with dragAndDrop() may be unsuitable for the application, or maybe the drag & drop should be performed with a mouse button other than the left button.

To achieve that one can make use of the following functions:

However, when doing so it is important to note that drag & drop typically requires some slow mouse movement at the starting point, after pressing and holding the mouse button, to be initiated, as can be seen in the example below.

Python

def main():
    #...

    o1 = waitForObject(...)
    drag_drop_start_qt(o1, MouseButton.RightButton)

    o2 = waitForObject(...)
    drag_drop_end_qt(o2, MouseButton.RightButton)

def drag_drop_start_qt(obj, mouseButton=None, modifierState=None, x_offset=5, y_offset=5):
    if mouseButton is None:
        mouseButton = MouseButton.LeftButton
    if modifierState is None:
        modifierState = 0
    mouseMove(obj)
    mousePress(obj, x_offset, y_offset, mouseButton, modifierState)

    # Move mouse cursor back and forth after
    # the button press to initiate drag &
    # drop:
    move_width = 10
    for i in range(move_width):
        snooze(0.05)
        mouseMove(obj, x_offset+i, y_offset)

    for i in range(move_width, -1, -1):
        snooze(0.05)
        mouseMove(obj, x_offset+i, y_offset)

def drag_drop_end_qt(obj, mouseButton=None, modifierState=None, x_offset=5, y_offset=5):
    if mouseButton is None:
        mouseButton = MouseButton.LeftButton
    if modifierState is None:
        modifierState = 0
    mouseMove(obj, x_offset, y_offset)
    mouseRelease(obj, x_offset, y_offset, mouseButton, modifierState)
test.py