Drag and Drop Robot Example

Demonstrates how to drag and drop items in a graphics view.

The Drag and Drop Robot example shows how to implement Drag and Drop in a QGraphicsItem subclass, as well as how to animate items using Qt’s Animation Framework .

../_images/dragdroprobot-example.png

Graphics View provides the QGraphicsScene class for managing and interacting with a large number of custom-made 2D graphical items derived from the QGraphicsItem class, and a QGraphicsView widget for visualizing the items, with support for zooming and rotation.

This example consists of a Robot class, a ColorItem class, and a main function: the Robot class describes a simple robot consisting of several RobotPart derived limbs, including RobotHead and RobotLimb, the ColorItem class provides a draggable colored ellipse, and the main() function provides the main application window.

We will first review the Robot class to see how to assemble the different parts so that they can be individually rotated and animated using QPropertyAnimation , and we will then review the ColorItem class to demonstrate how to implement Drag and Drop between items. Finally we will review the main() function to see how we can put all the pieces together, to form the final application.

Robot Class Definition

The robot consists of three main classes: the RobotHead, the RobotTorso, and the RobotLimb, which is used for the upper and lower arms and legs. All parts derive from the RobotPart class, which in turn inherits QGraphicsObject. The Robot class itself has no visual appearance and serves only as a root node for the robot.

Let’s start with the RobotPart class declaration.

class RobotPart(QGraphicsObject):

# public
    RobotPart(QGraphicsItem parent = None)
protected:
    def dragEnterEvent(event):
    def dragLeaveEvent(event):
    def dropEvent(event):
    color = Qt.lightGray()
    dragOver = False()

This base class inherits QGraphicsObject . QGraphicsObject provides signals and slots through inheriting QObject , and it also declares QGraphicsItem ‘s properties using Q_PROPERTY , which makes the properties accessible for QPropertyAnimation .

RobotPart also implements the three most important event handlers for accepting drop events: dragEnterEvent() , dragLeaveEvent() , and dropEvent() .

The color is stored as a member variable, along with the dragOver variable, which we will use later to indicate visually that the limb can accept colors that are is dragged onto it.

def __init__(self, parent):
    QGraphicsObject.__init__(self, parent)
    self.color = Qt.lightGray

    setAcceptDrops(True)

RobotPart's constructor initializes the dragOver member and sets the color to lightGray . In the constructor body we enable support for accepting drop events by calling setAcceptDrops(true) .

The rest of this class’s implementation is to support Drag and Drop.

def dragEnterEvent(self, event):

    if (event.mimeData().hasColor()) {
        event.setAccepted(True)
        dragOver = True
        update()
    else:
        event.setAccepted(False)

The dragEnterEvent() handler is called when a Drag and Drop element is dragged into the robot part’s area.

The handler implementation determines whether or not this item as a whole can accept the mime data assiciated with the incoming drag object. RobotPart provides a base behavior for all parts that accepts color drops. So if the incoming drag object contains a color, the event is accepted, we set dragOver to true and call update() to help provide positive visual feedback to the user; otherwise the event is ignored, which in turn allows the event to propagate to parent elements.

def dragLeaveEvent(self, event):

    Q_UNUSED(event)
    dragOver = False
    update()

The dragLeaveEvent() handler is called when a Drag and Drop element is dragged away from the robot part’s area. Our implementation simply resets dragOver to false and calls update() to help provide visual feedback that the drag has left this item.

def dropEvent(self, event):

    dragOver = False
    if (event.mimeData().hasColor())
        color = qvariant_cast<QColor>(event.mimeData().colorData())
    update()

The dropEvent() handler is called when a Drag and Drop element is dropped onto an item (i.e., when the mouse button is released over the item while dragging).

We reset dragOver to false, assign the item’s new color, and call update() .

The declaration and implementation of RobotHead, RobotTorso, and RobotLimb are practically identical. We will review RobotHead in detail, as this class has one minor difference, and leave the other classes as an exercise for the reader.

class RobotHead(RobotPart):

# public
    RobotHead(QGraphicsItem parent = None)
    boundingRect = QRectF()
    def paint(painter, option, None):
protected:
    def dragEnterEvent(event):
    def dropEvent(event):
# private
    pixmap = QPixmap()

The RobotHead class inherits RobotPart and provides the necessary implementations of boundingRect() and paint() . It also reimplements dragEnterEvent() and dropEvent() to provide special handling of image drops.

The class contains a private pixmap member that we can use to implement support for accepting image drops.

def __init__(self, parent):
    self.RobotPart = parent

RobotHead has a rather plain constructor that simply forwards to RobotPart's constructor.

def boundingRect(self):

    def QRectF(-15,-50,30,50):

The boundingRect() reimplementation returns the extents for the head. Because we want the center of rotation to be the bottom center of the item, we have chosen a bounding rectangle that starts at (-15, -50) and extends to 30 units wide and 50 units tall. When rotating the head, the “neck” will stay still while the top of the head tilts from side to side.

def paint(self, painter,):
           option, = QStyleOptionGraphicsItem()

    Q_UNUSED(option)
    Q_UNUSED(widget)
    if (pixmap.isNull()) {
        painter.setBrush(dragOver if color.lighter(130) else color)
        painter.drawRoundedRect(-10, -30, 20, 30, 25, 25, Qt.RelativeSize)
        painter.setBrush(Qt.white)
        painter.drawEllipse(-7, -3 - 20, 7, 7)
        painter.drawEllipse(0, -3 - 20, 7, 7)
        painter.setBrush(Qt.black)
        painter.drawEllipse(-5, -1 - 20, 2, 2)
        painter.drawEllipse(2, -1 - 20, 2, 2)
        painter.setPen(QPen(Qt.black, 2))
        painter.setBrush(Qt.NoBrush)
        painter.drawArc(-6, -2 - 20, 12, 15, 190 * 16, 160 * 16)
    else:
        painter.scale(.2272, .2824)
        painter.drawPixmap(QPointF(-15 * 4.4, -50 * 3.54), pixmap)

In paint() we draw the actual head. The implementation is split into two sections; if an image has been dropped onto the head, we draw the image, otherwise we draw a round rectangular robot head with simple vector graphics.

For performance reasons, depending on the complexity of what is painted, it can often be faster to draw the head as an image rather than using a sequence of vector operations.

def dragEnterEvent(self, event):

    if (event.mimeData().hasImage()) {
        event.setAccepted(True)
        dragOver = True
        update()
    else:
        RobotPart::dragEnterEvent(event)

The robot head can accept image drops. In order to support this, its reimplementation of dragEnterEvent() checks if the drag object contains image data, and if it does, then the event is accepted. Otherwise we fall back to the base RobotPart implementation.

def dropEvent(self, event):

    if (event.mimeData().hasImage()) {
        dragOver = False
        pixmap = qvariant_cast<QPixmap>(event.mimeData().imageData())
        update()
    else:
        RobotPart::dropEvent(event)

To follow up on image support, we must also implement dropEvent() . We check if the drag object contains image data, and if it does, we store this data as a member pixmap and call update() . This pixmap is used inside the paint() implementation that we reviewed before.

RobotTorso and RobotLimb are similar to RobotHead, so let’s skip directly to the Robot class.

class Robot(RobotPart):

# public
    Robot(QGraphicsItem parent = None)
    boundingRect = QRectF()
    def paint(painter, option, None):

The Robot class also inherits RobotPart, and like the other parts it also implements boundingRect() and paint() . It provides a rather special implementation, though:

def boundingRect(self):

    def QRectF():

def paint(self, painter,):
                  option, = QStyleOptionGraphicsItem()

    Q_UNUSED(painter)
    Q_UNUSED(option)
    Q_UNUSED(widget)

Because the Robot class is only used as a base node for the rest of the robot, it has no visual representation. Its boundingRect() implementation can therefore return a null QRectF , and its paint() function does nothing.

def __init__(self, parent):
    self.RobotPart = parent

    setFlag(ItemHasNoContents)
    torsoItem = RobotTorso(self)
    headItem = RobotHead(torsoItem)
    upperLeftArmItem = RobotLimb(torsoItem)
    lowerLeftArmItem = RobotLimb(upperLeftArmItem)
    upperRightArmItem = RobotLimb(torsoItem)
    lowerRightArmItem = RobotLimb(upperRightArmItem)
    upperRightLegItem = RobotLimb(torsoItem)
    lowerRightLegItem = RobotLimb(upperRightLegItem)
    upperLeftLegItem = RobotLimb(torsoItem)
    lowerLeftLegItem = RobotLimb(upperLeftLegItem)

The constructor starts by setting the flag ItemHasNoContents , which is a minor optimization for items that have no visual appearance.

We then construct all the robot parts (head, torso, and upper/lower arms and legs). The stacking order is very important, and we use the parent-child hierarchy to ensure the elements rotate and move properly. We construct the torso first, as this is the root element. We then construct the head and pass the torso to HeadItem's constructor. This will make the head a child of the torso; if you rotate the torso, the head will follow. The same pattern is applied to the rest of the limbs.

headItem.setPos(0, -18)
upperLeftArmItem.setPos(-15, -10)
lowerLeftArmItem.setPos(30, 0)
upperRightArmItem.setPos(15, -10)
lowerRightArmItem.setPos(30, 0)
upperRightLegItem.setPos(10, 32)
lowerRightLegItem.setPos(30, 0)
upperLeftLegItem.setPos(-10, 32)
lowerLeftLegItem.setPos(30, 0)

Each robot part is carefully positioned. For example, the upper left arm is moved precisely to the top-left area of the torso, and the upper right arm is moved to the top-right area.

animation = QParallelAnimationGroup(self)
headAnimation = QPropertyAnimation(headItem, "rotation")
headAnimation.setStartValue(20)
headAnimation.setEndValue(-20)
headScaleAnimation = QPropertyAnimation(headItem, "scale")
headScaleAnimation.setEndValue(1.1)
animation.addAnimation(headAnimation)
animation.addAnimation(headScaleAnimation)

The next section creates all animation objects. This snippet shows the two animations that operate on the head’s scale and rotation. The two QPropertyAnimation instances simply set the object, property, and respective start and end values.

All animations are controlled by one top-level parallel animation group. The scale and rotation animations are added to this group.

The rest of the animations are defined in a similar way.

for i in range(0, animation.animationCount()):
    anim = QPropertyAnimation (animation.animationAt(i))
    anim.setEasingCurve(QEasingCurve.SineCurve)
    anim.setDuration(2000)

animation.setLoopCount(-1)
animation.start()

Finally we set an easing curve and duration on each animation, ensure the toplevel animation group loops forever, and start the toplevel animation.

ColorItem Class Definition

The ColorItem class represents a circular item that can be pressed to drag colors onto robot parts.

class ColorItem(QGraphicsItem):

# public
    ColorItem()
    boundingRect = QRectF()
    def paint(painter, option, widget):
protected:
    def mousePressEvent(event):
    def mouseMoveEvent(event):
    def mouseReleaseEvent(event):
# private
    color = QColor()

This class is very simple. It does not use animations, and has no need for properties nor signals and slots, so to save resources, it’s most natural that it inherits QGraphicsItem (as opposed to QGraphicsObject ).

It declares the mandatory boundingRect() and paint() functions, and adds reimplementations of mousePressEvent() , mouseMoveEvent() , and mouseReleaseEvent() . It contains a single private color member.

Let’s take a look at its implementation.

def __init__(self):
    self.color = QRandomGenerator.global().bounded(256), QRandomGenerator.global().bounded(256), QRandomGenerator.global().bounded(256)

    setToolTip(QString("QColor(%1, %2, %3)\n%4")
              .arg(color.red()).arg(color.green()).arg(color.blue())
              .arg("Click and drag self color onto the robot!"))
    setCursor(Qt.OpenHandCursor)
    setAcceptedMouseButtons(Qt.LeftButton)

ColorItem's constructor assigns an opaque random color to its color member by making use of QRandomGenerator . For improved usability, it assigns a tooltip that provides a useful hint to the user, and it also sets a suitable cursor. This ensures that the cursor will chance to OpenHandCursor when the mouse pointer hovers over the item.

Finally, we call setAcceptedMouseButtons() to ensure that this item can only process LeftButton . This simplifies the mouse event handlers greatly, as we can always assume that only the left mouse button is pressed and released.

def boundingRect(self):

    def QRectF(-15.5,-15.5,34,34):

The item’s bounding rect is a fixed 30x30 units centered around the item’s origin (0, 0), and adjusted by 0.5 units in all directions to allow a scalable pen to draw its outline. For a final visual touch the bounds also compensate with a few units down and to the right to make room for a simple dropshadow.

def paint(self, painter, option, widget):

    Q_UNUSED(option)
    Q_UNUSED(widget)
    painter.setPen(Qt.NoPen)
    painter.setBrush(Qt.darkGray)
    painter.drawEllipse(-12, -12, 30, 30)
    painter.setPen(QPen(Qt.black, 1))
    painter.setBrush(QBrush(color))
    painter.drawEllipse(-15, -15, 30, 30)

The paint() implementation draws an ellipse with a 1-unit black outline, a plain color fill, and a dark gray dropshadow.

def mousePressEvent(self, arg__0):

    setCursor(Qt.ClosedHandCursor)

The mousePressEvent() handler is called when you press the mouse button inside the item’s area. Our implementation simply sets the cursor to ClosedHandCursor .

def mouseReleaseEvent(self, arg__0):

    setCursor(Qt.OpenHandCursor)

The mouseReleaseEvent() handler is called when you release the mouse button after having pressed it inside an item’s area. Our implementation sets the cursor back to OpenHandCursor . The mouse press and release event handlers together provide useful visual feedback to the user: when you move the mouse pointer over a CircleItem, the cursor changes to an open hand. Pressing the item will show a closed hand cursor. Releasing will restore to an open hand cursor again.

def mouseMoveEvent(self, event):

    if (QLineF(event.screenPos(), event.buttonDownScreenPos(Qt.LeftButton))
        .length() < QApplication.startDragDistance()) {
        return

    drag = QDrag(event.widget())
    mime = QMimeData()
    drag.setMimeData(mime)

The mouseMoveEvent() handler is called when you move the mouse around after pressing the mouse button inside the ColorItem's area. This implementation provides the most important piece of logic for CircleItem: the code that starts and manages drags.

The implementation starts by checking if the mouse has been dragged far enough to eliminate mouse jitter noise. We only want to start a drag if the mouse has been dragged farther than the application start drag distance.

Continuing, we create a QDrag object, passing the event widget (i.e., the QGraphicsView viewport) to its constructor. Qt will ensure that this object is deleted at the right time. We also create a QMimeData instance that can contain our color or image data, and assign this to the drag object.

n = 0
if (n++ > 2 and QRandomGenerator.global().bounded(3) == 0) {
    image = QImage(":/images/head.png")
    mime.setImageData(image)
    drag.setPixmap(QPixmap.fromImage(image).scaled(30, 40))
    drag.setHotSpot(QPoint(15, 30))

This snippet has a somewhat random outcome: once in a while, a special image is assigned to the drag object’s mime data. The pixmap is also assiged as the drag object’s pixmap. This will ensure that you can see the image that is being dragged as a pixmap under the mouse cursor.

else:
    mime.setColorData(color)
    mime.setText(QString("#%1%2%3")
                  .arg(color.red(), 2, 16, '0')
                  .arg(color.green(), 2, 16, '0')
                  .arg(color.blue(), 2, 16, '0'))
    pixmap = QPixmap(34, 34)
    pixmap.fill(Qt.white)
    painter = QPainter(pixmap)
    painter.translate(15, 15)
    painter.setRenderHint(QPainter.Antialiasing)
    paint(painter, None, None)
    painter.end()
    pixmap.setMask(pixmap.createHeuristicMask())
    drag.setPixmap(pixmap)
    drag.setHotSpot(QPoint(15, 20))

Otherwise, and this is the most common outcome, a simple color is assigned to the drag object’s mime data. We render this ColorItem into a new pixmap to give the user visual feedback that the color is being “dragged”.

drag.exec()
setCursor(Qt.OpenHandCursor)

Finally we execute the drag. exec() will reenter the event loop, and only exit if the drag has either been dropped, or canceled. In any case we reset the cursor to OpenHandCursor .

The main() Function

Now that the Robot and ColorItem classes are complete, we can put all the pieces together inside the main() function.

if __name__ == "__main__":

    app = QApplication([])

We start off by constructing QApplication , and initializing the random number generator. This ensures that the color items have different colors every time the application starts.

scene = QGraphicsScene(-200, -200, 400, 400)
for i in range(0, 10):
    item = ColorItem()
    item.setPos(::sin((i * 6.28) / 10.0) * 150,
                 ::cos((i * 6.28) / 10.0) * 150)
    scene.addItem(item)

robot = Robot()
robot.setTransform(QTransform.fromScale(1.2, 1.2), True)
robot.setPos(0, -20)
scene.addItem(robot)

We construct a fixed size scene, and create 10 ColorItem instances arranged in a circle. Each item is added to the scene.

In the center of this circle we create one Robot instance. The robot is scaled and moved up a few units. It is then added to the scene.

view = GraphicsView(scene)
view.setRenderHint(QPainter.Antialiasing)
view.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
view.setBackgroundBrush(QColor(230, 200, 167))
view.setWindowTitle("Drag and Drop Robot")
view.show()
sys.exit(app.exec())

Finally we create a QGraphicsView window, and assign the scene to it.

For increased visual quality, we enable antialiasing. We also choose to use bounding rectangle updates to simplify visual update handling. The view is given a fixed sand-colored background, and a window title.

We then show the view. The animations start immediately after control enters the event loop.

Example project @ code.qt.io