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?
To start a drag, create a QDrag object, and call its exec() function. In most applications, it is a good idea to begin a drag and drop operation only after a mouse button has been pressed and the cursor has been moved a certain distance.
Drag and drop is a functionality by which users can select an object or a section of text and can move it to a desired location and "drop" it there. Drag and drop is a part of most graphical user interfaces, but is not found in all software.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With