Qt Drag & Drop: Add support for dragging files to the application's main window

Cool_Coder picture Cool_Coder · Feb 15, 2013 · Viewed 15.9k times · Source

A lot of applications allow users to drag a file or files to the application's main window.

How do I add support for this feature in my own Qt application?

Answer

borisbn picture borisbn · Feb 15, 2013

Overload dragEnterEvent() and dropEvent() in your MainWindow class, and call setAcceptDrops() in the constructor:

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

void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
    if (e->mimeData()->hasUrls()) {
        e->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent *e)
{
    foreach (const QUrl &url, e->mimeData()->urls()) {
        QString fileName = url.toLocalFile();
        qDebug() << "Dropped file:" << fileName;
    }
}