R – Drag & drop with .ui files

drag and dropqtqt4

I'm having big troubles with drag & drop. I've created a new Qt Designer Form Class in which I have one QListWidget and one QWidget. Now I want to enable dragging & dropping between these two widgets.

The problem is, where can I add dragEnterEven(…), dragMoveEvent(…) etc. functions? I only have these class.h, class.cpp and class.ui files.

Any help is much appreciated!

-Samuli

Best Answer

First off, if you haven't read Qt's Drag and Drop documentation you really want to start there. What I'm going to tell you is a summary of what's there. You also should definitely look at the drag and drop examples once you've read the description of the process.

Secondly, and I apologize if I'm misreading this, your question makes it sound like you aren't quite familiar with C++. You want to declare methods in the .h file, and define them in the .cpp file. You can use the Designer to do some of that declaration of events, but you will need to define the implementation of those events in the .cpp. If that's not clear you will need to go read more about basic C++ first.

If you're ok with those basics, here's a short summary of how drag and drop works:

  • Dragging is done by:
    • Creating a QDrag. You want to do this in the event that triggers the drag, which is, in all cases I can think of a mouse-click (mousePressEvent or mouseMoveEvent -- which one depends on the exact behavior you want to see).
    • Encoding the data you want to be dragged. You do this using MIME-encoding, a standard way of marking what type of document is being dragged. (Examples include text, images, and most other media formats). Assume text for the simple case.
      • Create a QMimeData
      • Set data for the appropriate type (e.g. for text use QMimeData::setText)\
      • Add the mime data to the drag object with QDrag::setMimeData.
      • Call QDrag::exec on your drag object.
  • Dropping is done by:
    • Enabling the acceptDrops property on the given widget using QWidget::setAcceptDrops(true).
    • Define dropEvent on your widget to handle the drop. The data you set in the drag using setMimeData is available as a method of the drop event QDropEvent::mimeData. You need to extract the data out of it using the appropriate document type (e.g. text()).

Obviously this isn't complete, but drag and drop has enough steps that you really should read about them in detail once and look at some examples. This summary is meant to give you an idea of what you need to do.

Related Topic