Implementing Drag and Drop for general widgets
This post is based on the one existing on Qt documentation. That is a great guide where you can find a lot of information and how to implement Drag&Drop in your widgets. However, when we want to apply that behavior into our widgets we might miss some useful information. Let’s write some requirements for our Drag&Drop widgets and then we will see how we implement it step by step.
- Disable dropping widgets that are not the type we expect. We don’t want that anybody starts dropping any widget from other places like a view.
- Change the background color when we’re moving over the widget we want to drop. If we change the color while we’re moving over the widget it will help us to know the drop area we have available.
- Store an id (int) and a name (string) on our droppable widget from the widget we just dropped. Doing it this way we can save queries to the database asking for the information.
Drag and Drop in Custom Widgets (with custom data)
Implementing Drag functionality
The first thing we’ll do is to implement the drag functionality in our original widget. It is a two steps action: first we need to capture the mouse press event so we know the position we are starting to move. Then, during the mouse move event we’ll check that we’ve moved a certain distance so we’re sure that the user wants to drag and isn’t just a trembling hand. So far is the same code we can read in the Qt Documentation.
But, in addition to it, we want to send some data to the droppable widget. This is done by adding that data to the QMimeData object we’re sending with the format of a QByteArray:
Right now we can drag our widget and when we move our mouse, the QDrag action will be triggered containing the data we’ve chosen. Now we only need to configure the droppable widget to accept this action and to change the styles:
As we can see in the source file we’re using the property system of Qt for storing a variable called drop with a boolean value. Qt allows us to use that variable in the CSS to define different styles.
If you want a running project with working Drag&Drop widgets, you can visit the DragDropCustomWidgets project.