Question

I have a window with several containers. What is the simplest way to implement drag-n-drop between them?

Was it helpful?

Solution

You have to use a QDrag* object. Then reimplement:

virtual void mousePressEvent(QMouseEvent * event);
virtual void mouseReleaseEvent(QMouseEvent * event);
virtual void mouseMoveEvent(QMouseEvent *event);

Inside those event you will manage a starting point (where the drag starts) and an end point (where you drop the widget). You will also use the MIME protocol to permit the framework to manage the drag n drop operation.

A more useful article on Drag and drop is this: Drag 'n drop

OTHER TIPS

The easiest way, I suppose, would be to create eventFilter class, where you would filter drag and drop events and install it (someWidget->installEventFilter) to all of your widgets, where you want drag and drop. Example from docs - here

update:

The thing with eventfilter is that you don't need to subclass all of your widgets for them to have drag and drop. Just install filter on any widget you want to have dnd filter and it will have it.

As for filter itself, it not always blocks events etc (it wiil do that if that's your intention). It was just en example of how one can use it.

Just one of countless options with drag and drop: in dropEvent, dragMoveEvent, dragEnterEvent your filter will possible remember pointer to what you want to drop and in dropEvent emit signal with the object, that event holds pointer to and catch it with widget where you drop it, and that's it, any widget that have filter installed will have drag and drop.

The whole point of event filter is NOT to bother with subclassing and connecting EVERY single one widget if you have the common event type, you want to catch and process in the similar way, like drag and drop events for example.

I assumed that you know how to drag and drop, but thought that overriding events in all the widgets with the same code over and over and over again could be not that right. So i showed you, how it can be easily done with one eventfilter for all widgets you want to have drag and drop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top