The DropHandler tutorial shows how to receive drag-and-drop events from the operating system. In this tutorial, you will learn how to receive file lists that are dropped on top of the application. The drop event handling is implemented into a widget, that is called DropHandler.
We begin by including header files that declares the classes that we are going to use. The most important include files are DropEvent.hpp (for the DropEvent and DropListener classes), and Mime.cpp (for composing widgets out of MIME types).
Next we define a new widget that will receive the drop events from the operating system. To be able to receive drop events this class is derived from Radiant::DropListener, that defines an API for receiving drop events. DropHandler also inherits MultiWidgets::Widget so that it has hooks into the application scene, and can add new widgets to the application.
The constructor of the class is used for two purposes.
Firstly it adds this widget to the list of DropEvent listeners with the Radiant::DropEvent::addDropListener function call.
Secondly the constructor sets up CSS type, some default values, and adds a text label explaining the application usage.
The virtual destructor of the class is implemented, to follow C++ conventions. Without a virtual destructor, the class deletion might be incomplete, which can lead into memory leaks and other problems.
Drag-and-drop events from the operating system are delivered in the form of Radiant::DropEvent objects. These objects are received by defining a virtual function called dropEvent. The function returns true if the event was consumed by this listener, and false if the event is not consumed by this listener. In a simple case like this the return value makes little difference, but if there are multiple DropEvent listeners active it is usually important that only one of the listeners processes the event completely and acts on it (aka consumes the event).
The implementation of the dropEvent function iterates through the URLs found in the drop event, and creates widgets based on the URLs. The URLs are expected to be local files.
MultiWidgets::Mime class is used to create the new widgets, based on the file type. The Mime class simplifies our work, since it can automatically create widgets that can be used to display different file types (images, videos etc.).
The created widgets are placed on the location of the drop event.
Once the DropHandler class is implemented, we only need to create a normal application object and add one instance of the DropHandler class into it. Since the DropHandler can add the relevant listener hooks itself, there is no need for the application to do anything but add the DropHandler widget into the scene.
The full source code for the example is listed below: