[Qt-interest] Model/view conditionally accept dropped items

Robert Hairgrove evorgriahr at hispeed.ch
Tue Feb 16 21:53:07 CET 2010


Jugdish wrote:
> I have a model with items of certain "types" -- let's say type A, B, C, 
> D. The items of the model are drag/droppable, but I'd like it such that 
> an item accepts a drop only if the item being dragged is of the same 
> type. So, when dragging an item of type A, only other type "A" items 
> will accept the drop. Essentially, the state of each item's 
> Qt::ItemIsDropEnabled flag needs to dynamically update itself depending 
> on what item is being dragged. What is the best way to implement such 
> behavior?
> Thanks for your help.

You could just return from the receiving widget's dropEvent() instead of 
calling event->acceptProposedAction(), and nothing will be dropped. No 
need to change any flags. This is also possible from the 
dragMoveEvent().  Or you could reimplement the mousePressedEvent() and 
check there for the appropriate type before you start a drag action.

At any rate, you will need to deal with MIME data, so I would expose the 
type information about the data being dragged (somehow) in a custom MIME 
data format. Even if it is implemented as text, you can format it any 
way you wish and give it an appropriate MIME format (i.e. name for it 
such as "application/foo-data"). You would need to register it with the 
qRegisterMetaTypeStreamOperators() function before using it in drag & 
drop operations, though. This involves implementing stream operators for 
the type (i.e. operators >> and <<, etc.) Since QByteArray is usually 
used for passing around MIME data, it can also be in binary format.

Another, and possibly better approach, would be to have a different MIME 
type for each object type. Check out the overview for "Drag and Drop" in 
Qt Assistant as well as the example code given.



More information about the Qt-interest-old mailing list