summaryrefslogtreecommitdiff
path: root/src/dic-options/DraggableListModel.cpp
blob: 2ea052366893ca32d30c327e1031a7bf944fe7e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "DraggableListModel.h"
#include "../dictionary/CardPack.h"
#include "../dictionary/Field.h"

#include <QMimeData>

Qt::ItemFlags DraggableListModel::flags(const QModelIndex &index) const
    {
    Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);
    if (index.isValid())
        return Qt::ItemIsDragEnabled | defaultFlags;
    else
        return Qt::ItemIsDropEnabled | defaultFlags;
    }

Qt::DropActions DraggableListModel::supportedDropActions() const
    {
    return Qt::MoveAction;
    }

QStringList DraggableListModel::mimeTypes() const
    {
    QStringList types;
    types << "application/octet-stream";
    return types;
    }

QMimeData *DraggableListModel::mimeData(const QModelIndexList &indexes) const
    {
    QStringList list;
    QModelIndexList validIndexes;
    foreach (QModelIndex index, indexes)
        if (index.isValid() && index.column() == 0)
            validIndexes << index;
    qSort(validIndexes);

    int num = validIndexes.size();
    QByteArray encodedData;
    QDataStream stream( &encodedData, QIODevice::WriteOnly );
    const void** ptrs = new const void*[num];
    int i=0;
    foreach (QModelIndex index, validIndexes)
        ptrs[i++] = dataPtr( index );
    stream.writeBytes( (char*)ptrs, num*sizeof(void*) );
    delete ptrs;
    QMimeData *mimeData = new QMimeData();
    mimeData->setData( "application/octet-stream", encodedData );
    return mimeData;
    }

bool DraggableListModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
    int row, int /*column*/, const QModelIndex &parent)
    {
    if (action == Qt::IgnoreAction)
        return true;
    if (!data->hasFormat("application/octet-stream"))
        return false;

    int beginRow;
    if (row != -1)
        beginRow = row;
    else if (parent.isValid())
        beginRow = parent.row();
    else
        beginRow = rowCount(QModelIndex());

    QByteArray encodedData = data->data("application/octet-stream");
    QDataStream stream( &encodedData, QIODevice::ReadOnly );
    void** ptrs = new void*[ rowCount() ];
    uint num;
    stream.readBytes( (char*&)ptrs, num );   //TODO: Avoid converting pointer to other types
    num /= sizeof(void*);

    QList<QPersistentModelIndex> movedIndexes;
    for(uint i=0; i<num; i++)
        {
        insertPointer( beginRow + i, ptrs[i] );
        movedIndexes << QPersistentModelIndex( index(beginRow + i, 0, QModelIndex()) );
        }
    delete ptrs;
    emit indexesDropped( movedIndexes );
    return true;
    }