拖放QFrame

时间:2017-03-08 17:01:25

标签: qt drag-and-drop

我一直在看拖放示例,我仍然对它们感到困惑。特别是我不知道在mousePressEvent()和dropEvent()中做什么。

我正在关注并修改拖拽QLabel的示例。 以下是我认为mousePressEvent()应该是QFrame的样子。我试过了,我可以看到框架移动但是当我放下框架时我会失去它。

void SummaryBar::mousePressEvent(QMouseEvent *event)
{
    QFrame *child = static_cast<QFrame*>(childAt(event->pos()));
    if (!child)
        return;

    QPixmap pixmap = QPixmap::grabWidget(child);

    QByteArray itemData;
    QDataStream dataStream(&itemData, QIODevice::WriteOnly);
    dataStream << pixmap << QPoint(event->pos() - child->pos());

    QMimeData *mimeData = new QMimeData;
    mimeData->setData("application/x-dnditemdata", itemData);

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->setPixmap(pixmap);
    drag->setHotSpot(event->pos() - child->pos());


    if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
        child->close();
    } else {
        child->show();

    }
}

这是dropEvent()。它显然不起作用......不确定原因。

    void SummaryBar::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
        QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
        QDataStream dataStream(&itemData, QIODevice::ReadOnly);

        QPixmap pixmap;
        QPoint offset;
        dataStream >> pixmap >> offset;

        QFrame *newFrame = new QFrame(this);
        //newFrame->setPixmap(pixmap);
        newFrame->move(event->pos() - offset);
        newFrame->show();
        newFrame->setAttribute(Qt::WA_DeleteOnClose);

        if (event->source() == this) {
            event->setDropAction(Qt::MoveAction);  
            event->accept();
        } else {
            event->acceptProposedAction();
        }
    } else {
        event->ignore();
    }
}

void SummaryBar::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
        if (event->source() == this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }
    } else {
        event->ignore();
    }
}    

I would greatly appreciate any help!!

0 个答案:

没有答案