How to implement drag-n-dropping widget to another container in qt? [closed]

送分小仙女□ 提交于 2019-12-24 01:24:44

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/20002566/how-to-implement-drag-n-dropping-widget-to-another-container-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!