Search code examples
c++qtdrag-and-dropqt5

Qt Drop event not firing


Drop event will not happen, although `setAcceptDrops' has been called. The following code is based on a widget project created with Qt 5.12.0. After adding in dropEvent() function the cpp file becomes

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug> // added

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAcceptDrops(true); // added
}

MainWindow::~MainWindow()
{
    delete ui;
}

// added; in .h it is in `protected:' section
void MainWindow::dropEvent(QDropEvent *event)
{
    qDebug() << "dropEvent";
}

What am I missing? I have been struggling for a few days... Thanks in advance.


Solution

  • You have to overwrite the dragEnterEvent method that allow you to filter by the data type, by the source, by the type of action. In the following example, everything is accepted:

    *.h

    // ...
    protected:
        void dropEvent(QDropEvent *event) override;
        void dragEnterEvent(QDragEnterEvent *event) override;
    // ...
    

    *.cpp

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        setAcceptDrops(true); // added
    }
    
    // ...
    void MainWindow::dropEvent(QDropEvent *event)
    {
        qDebug() << "dropEvent" << event;
    }
    void MainWindow::dragEnterEvent(QDragEnterEvent *event)
    {
        event->acceptProposedAction();
    }
    

    For more detail I recommend you read Drag and Drop.