Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 489
Cool_Coder Avatar asked Feb 15 '13 13:02

Cool_Coder


People also ask

How do you drag in Qt?

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.

What is drag and drop function?

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.


1 Answers

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;     } } 
like image 142
borisbn Avatar answered Sep 22 '22 14:09

borisbn