【问题标题】:Accept Drag & Drop to QGraphicsScene接受拖放到 QGraphicsScene
【发布时间】:2019-11-15 20:27:58
【问题描述】:

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

QLabel 实现.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 是否可能“接受”下降,因此不会将其传播到场景?

标签: c++ qt


【解决方案1】:

您应该扩展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();
}

如果您在dragEnter 和dragMove 中没有acceptProposedAction(),您将永远不会触发dropEvent。

【讨论】:

    猜你喜欢
    • 2013-07-30
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2011-09-06
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多