Question

I'm writing a program where I need data from the QTreeWidgetItem that has been dropped into another part of my QTreeWidget. The drag and drop is working perfectly, and I am able to get a QEvent.Drop type event in my eventFilter. But I cant get the actual object that is being dropped, or any other data for that matter.

How can I get the object that is being dropped?

Was it helpful?

Solution

It is impossible to get the "object" (in a C++ sense) that is being dropped via an eventFilter or a reimplementation of a virtual dropEvent() method.

The reason is that the design of Drag and Drop under Qt is to make it cross-application, i.e. you can drag and drop "things" between two different applications. Hence, Application1 is not aware of the C++ classes used in Application2, and vice versa. Also, even if the same classes are used, the addresses used in Application1 are not accessible in Application2 (the OS doesn't allow a process to mess up with memory of another process). Hence, Drag and Drop events contains generic "data" instead, whose type and content is determined by a MIME type.

That being said, your case is not hopeless ;-) The QTreeWidgetItem object cannot be obtained, but the data it contains can be. To do this, you first need to get the MIME types that are used to describe the data contained in your QTreeWidgetItem, those are accessible via:

QStringList QTreeWidget::mimeTypes() const;

Note that this is a protected function, so instead of QTreeWidget, you must use your own class MyTreeWidget that inherits from it, and from which you can call this method (and possibly tell the rest of the world too). I advise you to print the result of this method to qDebug() to have an idea of how it looks like. In my case, this returns a list with only one MIME type: application/x-qabstractitemmodeldatalist. I guess it would be the same for you, but I don't know how it is implemented so you'd better checked it out by yourself.

Then, you can access the data associated to each MIME type (well, it seems there is only one MIME type...) using:

foreach(QString mimeType, mimeTypes)
{
    QByteArray array = dropEvent.mimeData()->data(mimeType);
}

Or probably just QByteArray array = dropEvent.mimeData()->data("application/x-qabstractitemmodeldatalist");.

Now, it is up to you to see how this looks like, and see if you can extract the information you need. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top