Accepting drops on a QGraphicsScene
Asked Answered
M

1

10

I'm trying to implement drag'n'drop for a QGraphicsScene. Here are the events I've overloaded:

void TargetScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
    bool acceptDrag = false;
    const QMimeData* mime = event->mimeData();

    // Is an image present?
    if (mime->hasImage()) {
        QImage img = qvariant_cast<QImage>(mime->imageData());
        dragPix = QPixmap::fromImage(img);
        acceptDrag = !dragPix.isNull();
    }

    event->setAccepted(acceptDrag);
}

void TargetScene::dropEvent(QGraphicsSceneDragDropEvent *event) {
    // Add dragged pixmap to scene
    QGraphicsPixmapItem* newPix = this->addPixmap(dragPix);
    newPix->setPos(event->pos().x(), event->pos().y());
}

The scene still won't accept drops. I'm guessing that's because I can't do setAcceptDrops(true) on my QGraphicsScene.

How do I accept drops on a graphics scene?

Marras answered 14/11, 2010 at 13:43 Comment(0)
L
14

The trick here is to ALSO accept the event in the QGraphicsScene::dragMoveEvent()!

The reason is the DEFAULT implementation which ignores drag and drop events if there is no item under the mouse!

Also refer to: http://www.qtcentre.org/threads/8022-QGraphicsScene-doesn-t-accept-Drops

Cheers

Lactiferous answered 12/12, 2010 at 13:18 Comment(1)
If you accept the drop in dragEnterEvent() then it's enough to just override dragMoveEvent() with an empty function, so as to avoid the default behavior of QGraphicsScene.Package

© 2022 - 2024 — McMap. All rights reserved.