PDA

View Full Version : QTreeView Drag and Drop to QtableView



chithara
24th June 2019, 10:23
HI,

I want to do dragging from QTreeView and dropping them into QTableView, but the data is not same. I need to take the indexes of all dragging nodes and its respective QTreeView class object while Dragging/dropping and will be displaying custom data in QTableView.

QTreeView whose model is derived from QAbstractItemModel.
QTableView with QStandardItemModel.

I have re-implemented the QMimeData* mimeData(const QModelIndexList &indexes) function in in my QTreeView model and dropEvent in QTableView. I am not sure, how to pass the object/indexes in mimeData() function and how can I retrieve the same in dropEvent() ? Currently, event->source() is coming as nullptr in dropEvent() :(

Any help?

d_stranz
24th June 2019, 16:29
You're trying to get an apple tree to grow oranges. As I am sure you realize, you can't copy a QModelIndex from one model to another, even if the two models are the same type (which in this case they are not).

Your QAbstractItemModel has an underlying data model of your own, right? So what you need to transfer is a pointer or some other reference to the specific item in that model to the table by way of the QMimeData instance so that the table can retrieve the information it needs.

QMimeData is derived from QObject, so one way might be to define a named property when you create the QMimeData at the start of the drag. See QObject::property() / QObject::setProperty(). This takes a QVariant as its type, so you could use the static method QVariant::fromValue() to create a QVariant storing the pointer to your internal data. Once the drop occurs, you can use the property to retrieve the QVariant and pointer and then populate the table.

Another possibility along these same lines is to store the QVariant-wrapped pointer in the QModelIndex itself using the QModelIndex::data() method. This would require you to implement a custom UserRole in your QAbstractItemModel that returns the QVariant-wrapped pointer, since QModelIndex::data() just calls QAbstractItemModel::data(). When your mime data containing the list of QModelIndex instances is dropped on your table, you can retrieve the variant for each index using QModelIndex::data(), passing Qt::UserRole as the role.

Since you have already implemented QMimeData for a list of QModelIndex instances, this second method is probably the least amount of additional work.