Matthias
Matthias

Reputation: 471

QListview Drag and Drop Slot

I have a QListView in my MainWindow and enabled drag and drop. For this I wanted to create a Slot witch is listening to the drag and drop events. But in the QT Documentation I didn't found a Signal for this event. How I can create a Slot or listen somehow to drag and drop events?

EDIT: I just want to Use Drag and Drop in ListView to reorder Items, and just Listen to this Event.

Upvotes: 0

Views: 1173

Answers (1)

Max Go
Max Go

Reputation: 2102

Implementation of Drag and Drop requires implementation of drag operation and drop operation in all widgets that will support it.

To implement Drag operation the best approach is to use overloading of mouse event handler in the widgets that should able to drag:

void DragWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        dragStartPosition = event->pos();
}

void DragWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (!(event->buttons() & Qt::LeftButton))
        return;
    if ((event->pos() - dragStartPosition).manhattanLength()
         < QApplication::startDragDistance())
        return;

    QDrag *drag = new QDrag(this);
    QMimeData *mimeData = new QMimeData;

    mimeData->setData(mimeType, data);
    drag->setMimeData(mimeData);

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

To be able to receive Drop events, it's needed to mark widget with setAcceptDrops(true) and overload dragEnterEvent() and dropEvent() event handler functions. For example:

Window::Window(QWidget *parent)
    : QWidget(parent)
{
    ...
    setAcceptDrops(true);
}

void Window::dropEvent(QDropEvent *event)
{
    textBrowser->setPlainText(event->mimeData()->text());
    mimeTypeCombo->clear();
    mimeTypeCombo->addItems(event->mimeData()->formats());

    event->acceptProposedAction();
}

You can find full documentation for this here.

Upvotes: 1

Related Questions