繁体   English   中英

接受拖放到 QGraphicsScene

[英]Accept Drag & Drop to QGraphicsScene

试图将 label 从 QWidget 拖放到 QGraphicsScene。 我已经从 QLabel 进行了自定义实现。 QGraphicsView 也接受丢弃。 问题是 QGraphicsScene 在将元素拖放到它时不会收到任何事件。

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);
    }
}

场景.cpp

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

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

我需要做什么才能让场景接收掉落?

您应该扩展QGraphicsView ,设置QGraphicsScene ,然后覆盖QGraphicsView拖放槽。

看看这个工作示例:

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();
}

如果您在dragEnterdragMove中不acceptProposedAction() ,您将永远不会触发dropEvent

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM