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?
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;
}
}
MainWindow::dragMoveEvent()
method too in which I just acceptProposedAction()
'd the event. Otherwise it wouldn't work for me.
viewport()
and not the direct widget itself.
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.