2

Using Qt to create an application that accepts a file drop. I have an area on my UI that I want to drop the file into, using a Qlabel. I have the function of dragging and dropping the file into the UI working, however I can drop it anywhere on the window, and not just into the Qlabel area.

I thought using

ui->label_drag->setAcceptDrops(true);

would work, however this just removed the functionality all together. What is the best way of handling this? if possible at all.

Thanks

Dimitry Ernot
  • 6,256
  • 2
  • 25
  • 37
ConnorDWP
  • 21
  • 3

1 Answers1

1

The best way to do this is to override the QLabel class. In the dragEnterEvent be sure to call acceptProposedAction to process the move and leave events. If you don't do that, only the dragEnter event will fire.

Sample code follows. To use this in your project, add the source to your project and then right click on the label on the form and promote the item to QLabelDragDrop.

#ifndef QLABELDRAGDROP_H
#define QLABELDRAGDROP_H

#include <QLabel>

class QLabelDragDrop : public QLabel
{
    Q_OBJECT
public:
    explicit QLabelDragDrop(QWidget *parent = nullptr);
protected:
    void dragEnterEvent(QDragEnterEvent *event);
    void dragLeaveEvent(QDragLeaveEvent *event);
    void dragMoveEvent(QDragMoveEvent *event);

signals:

public slots:
};

#endif // QLABELDRAGDROP_H
#include "qlabeldragdrop.h"
#include <QDebug>
#include <QDragEnterEvent>
#include <QDropEvent>

QLabelDragDrop::QLabelDragDrop(QWidget *parent) : QLabel(parent)
{
    setAcceptDrops(true);
    setMouseTracking(true);
}

void QLabelDragDrop::dragEnterEvent(QDragEnterEvent *event)
{
    qDebug() << "dragEnterEvent";
    event->acceptProposedAction();
}

void QLabelDragDrop::dragLeaveEvent(QDragLeaveEvent *event)
{
    qDebug() << "dragLeaveEvent";
    releaseMouse();
}

void QLabelDragDrop::dragMoveEvent(QDragMoveEvent *event)
{
    qDebug() << "dragMoveEvent";
}

void QLabelDragDrop::dropEvent(QDropEvent *event)
{
    qDebug() << "dropEvent";
}
Kevin
  • 16,549
  • 8
  • 60
  • 74
Mike Z
  • 21
  • 2