Drag and Drop of files on QMainWindows

Background / technical stuff

Drag and drop is done via some events:

  • void dragEnterEvent(QDragEnterEvent* event);
  • void dragMoveEvent(QDragMoveEvent* event);
  • void dragLeaveEvent(QDragLeaveEvent* event);
  • void dropEvent(QDropEvent* event);

They are called in order to let the application decide if it could accept a drag/drop or not. If the application says: do not accept this dragEnter event, then the OS will deny dropping of the content for the application. Same applies to the dragMoveEvent (perhaps, dropping is only allowed in special places, like toolbar etc.).

The dropp event is called, when the user drops his data. Inside the drop event, the widget must react on the different drop actions and the content type. e.g. (here we react on all actions):

  1. void DocumentWindow::dropEvent(QDropEvent* event)
  2. {
  3.     const QMimeData* mimeData = event->mimeData();
  4.  
  5.     // check for our needed mime type, here a file or a list of files
  6.     if (mimeData->hasUrls())
  7.     {
  8.         QStringList pathList;
  9.         QList<QUrl> urlList = mimeData->urls();
  10.  
  11.         // extract the local paths of the files
  12.         for (int i = 0; i < urlList.size() && i < 32; ++i)
  13.         {
  14.             pathList.append(urlList.at(i).toLocalFile());
  15.         }
  16.  
  17.         // call a function to open the files
  18.         openFiles(pathList);
  19.     }
  20. }

Use the DocumentWindow class

If you want to create an (MDI) editor application, you can derive your main window class from DocumentWindow instead of QMainWindow. If you implement an MDI application, you should also reimplement the virtual method ddeOpenFile.
The example code is based on the Qt MDI Example [doc.qt.nokia.com]

The only changes needed are:

  • derive from DocumentWindow instead of QMainWindow
  • implement the functions virtual bool openFiles(const QStringList& pathList);

  1. bool MainWindow::openFiles(const QStringList& pathList)
  2. {
  3.     bool success = true;
  4.     for (int i = 0; i < pathList.size() && i < 32; ++i)
  5.     {
  6.         MdiChild *child = createMdiChild();
  7.         if (child->loadFile(pathList.at(i)))
  8.         {
  9.             statusBar()->showMessage(tr("File loaded"), 2000);
  10.             child->show();
  11.         }
  12.         else
  13.         {
  14.             child->close();
  15.         }
  16.     }
  17.     return success;
  18. }

Use the DocumentWindow sources

DocumentWindow.h

  1. // -------------------------------------------------------------------------------------------------
  2. /**
  3.  *  @file
  4.  *  @brief
  5.  *  @author Gerolf Reinwardt
  6.  *  @date   30. march 2011
  7.  *
  8.  *  Copyright (c) 2011, Gerolf Reinwardt. All rights reserved.
  9.  *
  10.  *  Simplified BSD License
  11.  *
  12.  *  Redistribution and use in source and binary forms, with or without modification, are
  13.  *  permitted provided that the following conditions are met:
  14.  *
  15.  *  1. Redistributions of source code must retain the above copyright notice, this list of
  16.  *     conditions and the following disclaimer.
  17.  *
  18.  *  2. Redistributions in binary form must reproduce the above copyright notice, this list
  19.  *     of conditions and the following disclaimer in the documentation and/or other materials
  20.  *     provided with the distribution.
  21.  *
  22.  *  THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
  23.  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  24.  *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
  25.  *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  26.  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27.  *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  28.  *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  30.  *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  *
  32.  *  The views and conclusions contained in the software and documentation are those of the
  33.  *  authors and should not be interpreted as representing official policies, either expressed
  34.  *  or implied, of Gerolf Reinwardt.
  35.  */
  36. // -------------------------------------------------------------------------------------------------
  37.  
  38. #ifndef WIDGET_H
  39. #define WIDGET_H
  40.  
  41. // ----- general includes --------------------------------------------------------------------------
  42. #include <QtGui/QMainWindow>
  43. #include <QtCore/QStringList>
  44.  
  45. // ----- local includes ----------------------------------------------------------------------------
  46. // ----- pre defines -------------------------------------------------------------------------------
  47.  
  48. // ----- class definition --------------------------------------------------------------------------
  49. /**
  50.  *  @short
  51.  *
  52.  *  The usage is fairly easy. Derive your own MainWindow class from DocumentWindow instead of QMainWindow
  53.  *  and implement the pure virtual function openFiles.
  54.  *
  55.  *  @code
  56.     MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) :
  57.         DocumentWindow(parent, flags)
  58.     {
  59.         ...
  60.  
  61.         setWindowTitle(tr("MDI"));
  62.         setUnifiedTitleAndToolBarOnMac(true);
  63.     }
  64.     @endcode
  65.  *
  66.  *  Aditionally, the openFiles must be implermented:
  67.  *
  68.  *  @code
  69.         bool MyClass::openFiles(const QStringList& pathList)
  70.         {
  71.             bool success = true;
  72.             for (int i = 0; i < pathList.size() && i < 32; ++i)
  73.             {
  74.                 MdiChild *child = createMdiChild();
  75.                 if (child->loadFile(pathList.at(i)))
  76.                 {
  77.                     statusBar()->showMessage(tr("File loaded"), 2000);
  78.                     child->show();
  79.                 }
  80.                 else
  81.                 {
  82.                     child->close();
  83.                 }
  84.             }
  85.             return success;
  86.         }
  87.     @endcode
  88.  *
  89.  */
  90. class DocumentWindow : public QMainWindow
  91. {
  92.     Q_OBJECT
  93. public:
  94.     // ----- enums ---------------------------------------------------------------------------------
  95.     // ----- construction --------------------------------------------------------------------------
  96.     /**
  97.      *  Constructor.
  98.      *
  99.      *  Creates a DocumentWindow with a given @arg parent and @arg flags.
  100.      */
  101.     explicit DocumentWindow(QWidget* parent = 0, Qt::WindowFlags flags = 0);
  102.  
  103.     /**
  104.      *  Destructor
  105.      */
  106.     ~DocumentWindow();
  107.  
  108.     // ----- operators -----------------------------------------------------------------------------
  109.     // ----- methods -------------------------------------------------------------------------------
  110.     // ----- accessors -----------------------------------------------------------------------------
  111.     // ----- members -------------------------------------------------------------------------------
  112.  
  113. protected:
  114.     // ----- events --------------------------------------------------------------------------------
  115.     /**
  116.      *  this event is called when the mouse enters the widgets area during a drag/drop operation
  117.      */
  118.     void dragEnterEvent(QDragEnterEvent* event);
  119.  
  120.     /**
  121.      *  this event is called when the mouse moves inside the widgets area during a drag/drop operation
  122.      */
  123.     void dragMoveEvent(QDragMoveEvent* event);
  124.  
  125.     /**
  126.      *  this event is called when the mouse leaves the widgets area during a drag/drop operation
  127.      */
  128.     void dragLeaveEvent(QDragLeaveEvent* event);
  129.  
  130.     /**
  131.      *  this event is called when the drop operation is initiated at the widget
  132.      */
  133.     void dropEvent(QDropEvent* event);
  134.  
  135.     // ----- helpers -------------------------------------------------------------------------------
  136.     /**
  137.      *  This method must be implemented by the client. It is used to opened the dropped files.
  138.      *
  139.      *  @param pathList list of urls given by the drop event
  140.      *  @retval true if successfull otherwise false
  141.      *
  142.      *  Here is an example implementation:
  143.      *
  144.      *  @code
  145.         bool MyClass::openFiles(const QStringList& pathList)
  146.         {
  147.             bool success = true;
  148.             for (int i = 0; i < pathList.size() && i < 32; ++i)
  149.             {
  150.                 MdiChild *child = createMdiChild();
  151.                 if (child->loadFile(pathList.at(i)))
  152.                 {
  153.                     statusBar()->showMessage(tr("File loaded"), 2000);
  154.                     child->show();
  155.                 }
  156.                 else
  157.                 {
  158.                     child->close();
  159.                 }
  160.             }
  161.             return success;
  162.         }
  163.         @endcode
  164.      */
  165.     virtual bool openFiles(const QStringList& pathList) = 0;
  166.  
  167. private:
  168.     // ----- privat helpers ------------------------------------------------------------------------
  169.     // ----- members -------------------------------------------------------------------------------
  170.     // ----- not allowed members -------------------------------------------------------------------
  171. };
  172.  
  173. #endif // WIDGET_H

DocumentWindow.cpp

  1. // -------------------------------------------------------------------------------------------------
  2. /**
  3.  *  @file
  4.  *  @brief
  5.  *  @author Gerolf Reinwardt
  6.  *  @date   30.01.2011
  7.  *
  8.  *  Copyright (c) 2011, Gerolf Reinwardt. All rights reserved.
  9.  *
  10.  *  Simplified BSD License
  11.  *
  12.  *  Redistribution and use in source and binary forms, with or without modification, are
  13.  *  permitted provided that the following conditions are met:
  14.  *
  15.  *  1. Redistributions of source code must retain the above copyright notice, this list of
  16.  *     conditions and the following disclaimer.
  17.  *
  18.  *  2. Redistributions in binary form must reproduce the above copyright notice, this list
  19.  *     of conditions and the following disclaimer in the documentation and/or other materials
  20.  *     provided with the distribution.
  21.  *
  22.  *  THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
  23.  *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  24.  *  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
  25.  *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  26.  *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  27.  *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  28.  *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  30.  *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  *
  32.  *  The views and conclusions contained in the software and documentation are those of the
  33.  *  authors and should not be interpreted as representing official policies, either expressed
  34.  *  or implied, of Gerolf Reinwardt.
  35.  */
  36. // -------------------------------------------------------------------------------------------------
  37.  
  38. // ----- general includes --------------------------------------------------------------------------
  39. #include <QtGui/QDragEnterEvent>
  40. #include <QtGui/QDragLeaveEvent>
  41. #include <QtGui/QDragMoveEvent>
  42. #include <QtGui/QDropEvent>
  43. #include <QtCore/QMimeData>
  44. #include <QtCore/QUrl>
  45. #include <QtCore/QList>
  46.  
  47. // ----- local includes ----------------------------------------------------------------------------
  48. #include "documentwindow.h"
  49.  
  50.  
  51. // ----- construction ------------------------------------------------------------------------------
  52. DocumentWindow::DocumentWindow(QWidget* parent, Qt::WindowFlags flags) :
  53.     QMainWindow(parent, flags)
  54. {
  55.     setAcceptDrops(true);
  56. }
  57.  
  58. DocumentWindow::~DocumentWindow()
  59. {
  60. }
  61.  
  62. // ----- operators ---------------------------------------------------------------------------------
  63. // ----- methods -----------------------------------------------------------------------------------
  64. // ----- accessors ---------------------------------------------------------------------------------
  65. // ----- public slots ------------------------------------------------------------------------------
  66. // ----- protected slots ---------------------------------------------------------------------------
  67. // ----- events ------------------------------------------------------------------------------------
  68. void DocumentWindow::dragEnterEvent(QDragEnterEvent* event)
  69. {
  70.     // if some actions should not be usable, like move, this code must be adopted
  71.     event->acceptProposedAction();
  72. }
  73.  
  74. void DocumentWindow::dragMoveEvent(QDragMoveEvent* event)
  75. {
  76.     // if some actions should not be usable, like move, this code must be adopted
  77.     event->acceptProposedAction();
  78. }
  79.  
  80.  
  81. void DocumentWindow::dragLeaveEvent(QDragLeaveEvent* event)
  82. {
  83.     event->accept();
  84. }
  85.  
  86. void DocumentWindow::dropEvent(QDropEvent* event)
  87. {
  88.     const QMimeData* mimeData = event->mimeData();
  89.  
  90.     if (mimeData->hasUrls())
  91.     {
  92.         QStringList pathList;
  93.         QList<QUrl> urlList = mimeData->urls();
  94.  
  95.         for (int i = 0; i < urlList.size() && i < 32; ++i)
  96.         {
  97.             pathList.append(urlList.at(i).toLocalFile());
  98.         }
  99.  
  100.         if(openFiles(pathList))
  101.             event->acceptProposedAction();
  102.     }
  103. }
  104.  
  105. // ----- private slots -----------------------------------------------------------------------------
  106. // ----- private helpers ---------------------------------------------------------------------------

You may use this code without any warranty.

Future extensions / combinations

typically I would use this together with a file type assignment [developer.qt.nokia.com] on windows

The code of the class and a demo project are located on gitorious in the following repository: qtdevnet-dropfiles [gitorious.org]

Versions

The current code is version 1 of the code.

Version 1

This marks the first public release.

Feedback

I would really welcome feedback on this class. If you spot big weaknesses, please let me know.

Categories: