-
Notifications
You must be signed in to change notification settings - Fork 13
/
reorderable_list_model.py
203 lines (174 loc) · 6.67 KB
/
reorderable_list_model.py
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import sys
from PyQt5 import QtWidgets, QtCore
class ReorderableListModel(QtCore.QAbstractListModel):
'''
ReorderableListModel is a list model which implements reordering of its
items via drag-n-drop
'''
dragDropFinished = QtCore.pyqtSignal()
def __init__(self, parent=None):
QtCore.QAbstractItemModel.__init__(self, parent)
self.nodes = ['node0', 'node1', 'node2', 'node3', 'node4', 'node5']
self.lastDroppedItems = []
self.pendingRemoveRowsAfterDrop = False
def rowForItem(self, text):
'''
rowForItem method returns the row corresponding to the passed in item
or None if no such item exists in the model
'''
try:
row = self.nodes.index(text)
except ValueError:
return None
return row
def index(self, row, column, parent):
if row < 0 or row >= len(self.nodes):
return QtCore.QModelIndex()
return self.createIndex(row, column)
def parent(self, index):
return QtCore.QModelIndex()
def rowCount(self, index):
if index.isValid():
return 0
return len(self.nodes)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole:
row = index.row()
if row < 0 or row >= len(self.nodes):
return None
return self.nodes[row]
else:
return None
def supportedDropActions(self):
return QtCore.Qt.MoveAction
def flags(self, index):
if not index.isValid():
return QtCore.Qt.ItemIsEnabled
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | \
QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled
def insertRows(self, row, count, index):
if index.isValid():
return False
if count <= 0:
return False
# inserting 'count' empty rows starting at 'row'
self.beginInsertRows(QtCore.QModelIndex(), row, row + count - 1)
for i in range(0, count):
self.nodes.insert(row + i, '')
self.endInsertRows()
return True
def removeRows(self, row, count, index):
if index.isValid():
return False
if count <= 0:
return False
num_rows = self.rowCount(QtCore.QModelIndex())
self.beginRemoveRows(QtCore.QModelIndex(), row, row + count - 1)
for i in range(count, 0, -1):
self.nodes.pop(row - i + 1)
self.endRemoveRows()
if self.pendingRemoveRowsAfterDrop:
'''
If we got here, it means this call to removeRows is the automatic
'cleanup' action after drag-n-drop performed by Qt
'''
self.pendingRemoveRowsAfterDrop = False
self.dragDropFinished.emit()
return True
def setData(self, index, value, role):
if not index.isValid():
return False
if index.row() < 0 or index.row() > len(self.nodes):
return False
self.nodes[index.row()] = str(value)
self.dataChanged.emit(index, index)
return True
def mimeTypes(self):
return ['application/vnd.treeviewdragdrop.list']
def mimeData(self, indexes):
mimedata = QtCore.QMimeData()
encoded_data = QtCore.QByteArray()
stream = QtCore.QDataStream(encoded_data, QtCore.QIODevice.WriteOnly)
for index in indexes:
if index.isValid():
text = self.data(index, 0)
stream << QtCore.QByteArray(text.encode('utf-8'))
mimedata.setData('application/vnd.treeviewdragdrop.list', encoded_data)
return mimedata
def dropMimeData(self, data, action, row, column, parent):
if action == QtCore.Qt.IgnoreAction:
return True
if not data.hasFormat('application/vnd.treeviewdragdrop.list'):
return False
if column > 0:
return False
num_rows = self.rowCount(QtCore.QModelIndex())
if num_rows <= 0:
return False
if row < 0:
if parent.isValid():
row = parent.row()
else:
return False
encoded_data = data.data('application/vnd.treeviewdragdrop.list')
stream = QtCore.QDataStream(encoded_data, QtCore.QIODevice.ReadOnly)
new_items = []
rows = 0
while not stream.atEnd():
text = QtCore.QByteArray()
stream >> text
text = bytes(text).decode('utf-8')
index = self.nodes.index(text)
new_items.append((text, index))
rows += 1
self.lastDroppedItems = []
for (text, index) in new_items:
target_row = row
if index < row:
target_row += 1
self.beginInsertRows(QtCore.QModelIndex(), target_row, target_row)
self.nodes.insert(target_row, self.nodes[index])
self.endInsertRows()
self.lastDroppedItems.append(text)
row += 1
self.pendingRemoveRowsAfterDrop = True
return True
class SelectionModel(QtCore.QItemSelectionModel):
def __init__(self, parent=None):
QtCore.QItemSelectionModel.__init__(self, parent)
def onModelItemsReordered(self):
new_selection = QtCore.QItemSelection()
new_index = QtCore.QModelIndex()
for item in self.model().lastDroppedItems:
row = self.model().rowForItem(item)
if row is None:
continue
new_index = self.model().index(row, 0, QtCore.QModelIndex())
new_selection.select(new_index, new_index)
self.clearSelection()
flags = QtCore.QItemSelectionModel.ClearAndSelect | \
QtCore.QItemSelectionModel.Rows | \
QtCore.QItemSelectionModel.Current
self.select(new_selection, flags)
self.setCurrentIndex(new_index, flags)
class MainForm(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.model = ReorderableListModel()
self.selectionModel = SelectionModel(self.model)
self.model.dragDropFinished.connect(self.selectionModel.onModelItemsReordered)
self.view = QtWidgets.QListView()
self.view.setModel(self.model)
self.view.setSelectionModel(self.selectionModel)
self.view.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
self.view.setDragDropOverwriteMode(False)
self.setCentralWidget(self.view)
def main():
app = QtWidgets.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()