I have a class which inherits QAbstractTableModel, and holds some complex structs in a QMap. The QVariant data(QModelIndex index, ...)
method just returns an enum which describes how a custom item delegate should draw the contents of a cell. I would like to implement drag and drop functionality in this model so th开发者_开发知识库at users can reorder these structs in the QMap, but can't quite figure our how Qt would like me to do this. All I need is to see the source and destination indices of the drag/drop operation and I can take care of the rest, but the closest thing I've found in QAbstractItemModel is the dropMimeData() function. DropMimeData() doesn't give me the source index and requires me to convert the data into some MIME type (plaintext, etc.), which it is definitely not. I can hack my way through this by creating a QMimeData that just contains the source index, but I would like to really learn to use Qt as it's meant to be used, and I feel like I'm missing something. Any thoughts?
Just to help clarify a bit, the application is an animation program which acts sort of like Adobe Flash. The class which inherits QAbstractTableModel has a QMap<int, FrameState>
(with struct FrameState{QPointF pos; bool visible;}
) to hold keyframes. This state of this QMap is what I would like to display and have users edit. I draw a green circle if there is a visible key frame, a red circle if there is an invisible keyframe, a line if the previous keyframe was visible, and nothing if the previous keyframe was invisible. I would like users to be able to drag the keyframes around to change their QMap key.
Thanks!
You can use the views dragEnterEvent
to get the indices that were selected initially:
void DropTreeView::dragEnterEvent(QDragEnterEvent *event)
{
QTreeView::dragEnterEvent(event);
const QItemSelectionModel * sm = selectionModel();
if (!sm)
return;
dragStartIndicies = sm->selectedIndexes();
}
You'll need to use the mime-types for the drag and drop, but C++ Qt provides a nice way to do that using QDataStream
:
QMimeData *YourModel::mimeData( const QModelIndexList &indexes ) const
{
QByteArray encodedData;
QDataStream stream( &encodedData, QIODevice::WriteOnly );
stream << yourQMap /* OR almost any Qt data structure */;
QMimeData *mData = new QMimeData();
mData->setData( YOUR_MIME_TYPE, encodedData );
return mData;
}
On the receiving end, you can get your data structure (i.e. QMap
if that's what you want to use) back out of the QDataStream
:
QByteArray encodedData = yourMimeData->data( YOUR_MIME_TYPE );
QDataStream stream( &encodedData, QIODevice::ReadOnly );
QMap decodedMap;
stream >> decodedMap;
精彩评论