0
votes

Trying to drag & drop label from QWidget to QGraphicsScene. I have made custom implementation from QLabel. Also QGraphicsView is accepting drops. The problem is that QGraphicsScene doens't get any events when dropping element to it.

QLabel implementation .cpp

void ItemLabel::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == Qt::LeftButton){
       QDrag *drag = new QDrag(this);
       QMimeData *mimeData = new QMimeData;

       mimeData->setText("Test");
       drag->setMimeData(mimeData);
       drag->setPixmap(*this->pixmap());
       drag->exec();

       Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
    }
}

Scene .cpp

void Scene::dropEvent(QGraphicsSceneDragDropEvent  *event)
{
    event->acceptProposedAction();
    qDebug() << "drop";
}

void Scene::dragEnterEvent(QGraphicsSceneDragDropEvent  *event)
{
    if(event->mimeData()->hasFormat("text/plain"))
        event->acceptProposedAction();
}

What I need to do to get scene receive drops?

1
Does QGraphicsView perhaps "accept" the drop and thus not propagate it to the scene?Developer Paul

1 Answers

0
votes

You should extend a QGraphicsView, set up a QGraphicsScene and then override the QGraphicsView drag/drop slots.

Take a look at this working sample:

MyGraphicsView::MyGraphicsView(QObject *p_parent):
    QGraphicsView(),
    m_scene(nullptr)
{ 

    ...
    m_scene = new QGraphicsScene(rect(), p_parent);
    setScene(m_scene);
    setAcceptDrops(true);
}


void MyGraphicsView::dragEnterEvent(QDragEnterEvent *p_event)
{
    p_event->acceptProposedAction();
}

void MyGraphicsView::dragMoveEvent(QDragMoveEvent *p_event)
{
    p_event->acceptProposedAction();
}

void MyGraphicsView::dropEvent(QDropEvent *p_event)
{
    p_event->acceptProposedAction();
}

If you do not acceptProposedAction() in dragEnter and dragMove, you will never get dropEvent triggered.