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;
}
}