PDA

View Full Version : Dragging a pointer



Cruz
29th January 2009, 10:49
Hi!

I feel the need to drag and drop a pointer to an object (application internally only), but my skills are too weak to accomplish this.

I figure the way to do it is to construct a QByteArray from a pointer to MyObject and put it into a QMimeData object.

Drag:


MyObject *myobject = new MyObject();

QMimeData *mimeData = new QMimeData;
mimeData->setData("myobject/pointer", QByteArray( (char*)&myobject, sizeof(myobject) ));



This code takes the address of the myobject pointer and converts it to a char pointer. That char pointer is passed as argument to the QByteArray constructor along with the right size, so that the QByteArray should contain the bytes of the address of my object. Right?

Now the unwrapping in the drop:



MyObject* p;
char* data = event->mimeData()->data("myobject/pointer").data();
p = (MyObject*)(*data);
qDebug() << p;
/* BOOM */


mimeData()->data() returns a QByteArray.
QByteArray.data() returns a char* to the data.
So I hoped to take the contents of the data with *data and cast it to a pointer to MyObject, but it crashes.

Little help please?

spirit
29th January 2009, 11:08
maybe better keep objects in QMap or in a QHash and pass object id through d&d and then get the pointer from QMap by id.

wysota
29th January 2009, 11:45
You are storing a (temporary) pointer to a pointer to an object, not a pointer to an object.

Cruz
29th January 2009, 13:24
It works like this:



MyObject* p;
memcpy(&p, event->mimeData()->data("myobject/pointer").data(), sizeof(p));

chezifresh
10th July 2009, 03:51
How might you accomplish this in python? I'd rather not serialize my objects (which are not QObjects), I want to add mime data for it so I can drag to the desktop and other applications but when dragging internally I really don't want to deal with the overhead.

Is it possible to subclass QDrag, and add a MyDragClass.object() or something along those lines? (requires an isinstance(MyDragClass, dragObject) in lots of places though)