What I want to do is very similar to this. Except that I am working with a QAbstractItemModel that has a tree structure and am interested in more than just the row and column. In fact, in my model, column is always 0. But in order to implement drag and drop, I need to get the parent, children, and the opaque pointer that internalPointer() returns. Here is some relevant code. CTreeView extends QTreeView.
void CTreeView::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist"))
{
event->acceptProposedAction();
}
}
void CTreeView::dropEvent(QDropEvent* event)
{
const QMimeData* mime_data = event->mimeData();
QByteArray encoded_data =
mime_data->data("application/x-qabstractitemmodeldatalist");
QDataStream stream(&encoded_data, QIODevice::ReadOnly);
while (!stream.atEnd())
{
// I can do this.
int row, column;
stream >> row >> column;
// But how do I construct the QModelIndex to get the parent, children,
// and opaque pointer?
// I have seen other advice that mentions doing this.
QMap<int, QVariant> role_data_map;
stream >> row >> col >> role_data_map;
// Which allows you to do this.
QList<int> keys = role_data_map.keys();
BOOST_FOREACH(int key, keys)
{
QVariant variant = role_data_map[key];
// use the variant
}
// But that only gets me part of the way there.
}
}
Any ideas? I only want to support drag and drop within the tree view so I'm thinking about storing the QModelIndexList of selectedIndexes() in a member variable of my subclass and just manipulating it directly in dropEvent(). That seems like cheating somehow so I'm still interested in the Qt way. Please let me know what you think of this idea.