Qt: Pass pointer to QObject in QMimeData
Is it possible to pass a pointer to a QObject using QMimeData during drag-and-drop operation? QMimeData only has this function for storing data:
void QMimeData::setData开发者_JAVA技巧(constQString &mimeType, const QByteArray &data)
but I can't find a way to safely encode a pointer into a QByteArray.
To clarify my goal: I need to pass a pointer to a QObject from a model to the target widget during the drag-and-drop operation.
Edit: As far as I undrestand Mime data is all about passing application independent data from one place to another: urls, colors, html code. In my case I need to pass a pointer to a resource object eithin the application. How to you usually deal with this kind of drag-drops?
Thanks Anton
You can subclass QMimeData and pass whatever you want.
To be on the safe & elegant side, I would come up with unique identifiers (e.g. strings, or numbers) for my objects and pass them as mime objects. Resolving a string back into the corresponding object using QHashmap is fast enough for your purpose.
The dirtiest (not recommended!) way would be that the identifier is the pointer address as int.
If you pass mime data with user interaction, you never know where it goes. If the user drops your pointer onto another application's window, it should fullfill the user's expectations best. An application that gets a mangled up mime object and crashes for it is worst. An application that gets a descriptive string and enables the user to understand what he was dropping is probably best.
I know that you can also, using the mime type, somewhat direct where the payload may be dropped and where not. the quintessence however is that you should stay within the mime concept. And that includes not passing a raw pointer.
As Kash said and the Qt docs suggest, subclass QMimeData.
Then, add the following:
- text/plain data describing or representing the dragged object, so if you drop this data to notepad.exe, it results in something relevant
- custom data type with an identifier or token that enables you to know that some dropped mime data is actually your subclass
- add your own data in the subclass
You will still need to test the qobject_cast (or dynamic_cast), because some other program might have proxied your mime data object.
精彩评论