29

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?

2 Answers 2

50

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;
    }
}
2
  • 2
    Just a note: I had to override the MainWindow::dragMoveEvent() method too in which I just acceptProposedAction()'d the event. Otherwise it wouldn't work for me.
    – Ancurio
    Dec 21, 2013 at 13:55
  • 2
    For those wanting to drop into container type widgets such as listview etc, you perform on their viewport() and not the direct widget itself.
    – iKlsR
    Oct 11, 2017 at 21:16
7

First, check Qt Reference Documentation: Drag and Drop for the fundamentals, and then take a look at Drag and Drop of files on QMainWindows for the technical stuff. The latter provides a complete example.

Qt also has a bunch of Drag and Drop examples, you might be interested in the Drop Site.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.