-
Notifications
You must be signed in to change notification settings - Fork 2
/
tabs_tableview.py
590 lines (446 loc) · 16.5 KB
/
tabs_tableview.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
from typing import List
from typing import Any
from typing import Dict
from typing import cast
from PySide6 import QtCore
from PySide6 import QtGui
from PySide6 import QtWidgets
class TabItem:
def __init__(self, data):
self.x = data.get("center", [10, 10])[0]
self.y = data.get("center", [10, 10])[1]
self.radius = data.get("radius", 5)
# not in the data
self.enabled = data.get("enabled", False)
def put_value(self, attr, value):
""" """
setattr(self, attr, value)
def __str__(self):
""" """
return "tab: [%f:%f] %f - %s" % (self.x, self.y, self.radius, self.enabled)
def to_dict(self) -> Dict[str, Any]:
""" """
return {
"center": [self.x, self.y],
"radius": self.radius,
"enabled": self.enabled,
}
class PyCutDoubleSpinBox(QtWidgets.QDoubleSpinBox):
""" """
def __init__(self, parent):
""" """
QtWidgets.QDoubleSpinBox.__init__(self, parent)
self.o = None
self.attribute = ""
self.setMinimum(0)
self.setMaximum(1000)
self.setSingleStep(1.0)
self.valueChanged.connect(self.cb_spinbox)
def cb_disconnect(self):
""" """
self.valueChanged.disconnect(self.cb_spinbox)
def cb_connect(self):
""" """
self.valueChanged.connect(self.cb_spinbox)
def assign_object(self, o):
""" """
self.o = o
def assign_object_attribute(self, attribute):
""" """
self.attribute = attribute
def set_value(self):
""" """
self.cb_disconnect()
try:
val = getattr(self.o, self.attribute)
except Exception:
val = 0
self.setValue(val)
self.cb_connect()
def cb_spinbox(self):
""" """
val = self.value()
self.o.put_value(self.attribute, val)
class PyCutDoubleSpinBoxDelegate(QtWidgets.QItemDelegate):
def __init__(self, parent):
QtWidgets.QItemDelegate.__init__(self, parent)
def createEditor(
self, parent, option, index: QtCore.QModelIndex | QtCore.QPersistentModelIndex
):
editor = PyCutDoubleSpinBox(parent)
model = cast(PyCutSimpleTableModel, index.model())
tab = model.get_tab(index)
attr = model.get_tab_attr(index)
editor.assign_object(tab)
editor.assign_object_attribute(attr)
# to flush an "setModelData" in place - it works!
editor.valueChanged.connect(self.onEditorValueChanged)
return editor
def onEditorValueChanged(self):
editor = self.sender()
if editor:
self.commitData.emit(editor)
def setEditorData(
self,
spinBox: PyCutDoubleSpinBox, # type: ignore [override]
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
):
spinBox = cast(PyCutDoubleSpinBox, spinBox)
spinBox.set_value()
def setModelData(
self,
spinBox: PyCutDoubleSpinBox, # type: ignore [override]
model,
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
):
model.handleNewvalue(index, cast(PyCutDoubleSpinBox, spinBox).value())
def updateEditorGeometry(
self,
editor: PyCutDoubleSpinBox, # type: ignore [override]
option,
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
):
editor.setGeometry(option.rect)
class PyCutCheckBox(QtWidgets.QCheckBox):
""" """
def __init__(self, parent):
""" """
QtWidgets.QCheckBox.__init__(self, parent)
self.o = None
self.attribute = ""
self.stateChanged.connect(self.cb_checkbox)
def cb_disconnect(self):
""" """
self.stateChanged.disconnect(self.cb_checkbox)
def cb_connect(self):
""" """
self.stateChanged.connect(self.cb_checkbox)
def assign_object(self, o):
""" """
self.o = o
def assign_object_attribute(self, attribute):
""" """
self.attribute = attribute
def set_value(self):
""" """
self.cb_disconnect()
uival = {True: QtCore.Qt.Checked, False: QtCore.Qt.Unchecked}[
getattr(self.o, self.attribute)
]
self.setCheckState(uival)
self.cb_connect()
def cb_checkbox(self, index):
""" """
val = {QtCore.Qt.Checked: True, QtCore.Qt.Unchecked: False}[self.checkState()]
self.o.put_value(self.attribute, val)
class PyCutCheckBoxDelegate(QtWidgets.QStyledItemDelegate):
def createEditor(
self, parent, option, index: QtCore.QModelIndex | QtCore.QPersistentModelIndex
):
editor = PyCutCheckBox(parent)
model = cast(PyCutSimpleTableModel, index.model())
tab = model.get_tab(index)
attr = model.get_tab_attr(index)
editor.assign_object(tab)
editor.assign_object_attribute(attr)
# return editor # -> ugly checkbox on the left of the cell
# -> for checkboxes to be centered: embed into a widget
checkWidget = QtWidgets.QWidget(parent)
checkLayout = QtWidgets.QHBoxLayout(checkWidget)
checkLayout.addWidget(editor)
checkLayout.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
checkLayout.setContentsMargins(0, 0, 0, 0)
# to flush an "setModelData" in place - it works!
editor.stateChanged.connect(self.onEditorStateChanged)
return checkWidget
def onEditorStateChanged(self):
editor = self.sender()
if editor:
checkWidget = editor.parent()
self.commitData.emit(checkWidget)
def setEditorData(
self,
checkWidget: QtWidgets.QWidget,
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
):
checkBoxItem = checkWidget.layout().itemAt(0)
checkBox = cast(PyCutCheckBox, checkBoxItem.widget())
checkBox.set_value()
def setModelData(
self,
checkWidget: QtWidgets.QWidget,
model,
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
):
checkBoxItem = checkWidget.layout().itemAt(0)
checkBox = cast(PyCutCheckBox, checkBoxItem.widget())
model.handleNewvalue(index, checkBox.isChecked())
def updateEditorGeometry(
self, editor, option, index: QtCore.QModelIndex | QtCore.QPersistentModelIndex
):
editor.setGeometry(option.rect)
class PyCutTabsTableViewManager(QtWidgets.QWidget):
def __init__(self, parent):
""" """
QtWidgets.QWidget.__init__(self, parent)
self.mainwindow = None
self.svg_viewer = None
self.model = None
# main section of the window
vbox = self.vbox = QtWidgets.QVBoxLayout()
vbox.setContentsMargins(0, 0, 0, 0)
# let's add two views of the same data source we just created:
self.table = PyCutSimpleTableView(self)
self.table.resizeColumnsToContents()
self.table.setMinimumWidth(300)
# bottom section of the window:
# let's have a text input and a pushbutton that add an item to our model.
hbox = QtWidgets.QHBoxLayout()
# create the button, and hook it up to the slot below.
self._button_add = QtWidgets.QPushButton("Create Tab")
self._button_add.clicked.connect(self.add_item)
self._button_add.setIcon(QtGui.QIcon(":/images/tango/32x32/actions/list-add"))
hbox.addWidget(self._button_add)
# add bottom to main window layout
vbox.addLayout(hbox)
vbox.addWidget(self.table)
vbox.setStretch(1, 1)
# set layout on the window
self.setLayout(vbox)
def set_svg_viewer(self, svg_viewer):
""" """
self.svg_viewer = svg_viewer
self.mainwindow = svg_viewer.mainwindow
def set_tabs(self, tabs):
""" """
cnc_tabs = []
for tab in tabs:
cnc_tab = TabItem(tab)
cnc_tabs.append(cnc_tab)
self.model = PyCutSimpleTableModel(cnc_tabs, self.mainwindow)
self.table.setModel(self.model)
self.table.setup()
self.vbox.addWidget(self.table)
def get_tabs(self) -> List[Dict]:
"""
returns the list of tabs ready to be saved as json data
"""
tabs: List[Dict] = []
for tab in self.get_model_tabs():
atab = tab.to_dict()
tabs.append(atab)
return tabs
def set_model(self, model):
""" """
self.table.setModel(model)
def get_model(self) -> "PyCutSimpleTableModel":
""" """
return self.table.model()
def get_model_tabs(self) -> List[TabItem]:
""" """
return self.get_model().tabs
def add_item(self):
"""
instruct the model to add an item
"""
self.table.add_item({"center": [10, 10], "radius": 5, "enabled": True})
print("ADD")
for tab in self.get_model_tabs():
print(tab)
# inform main window (draw tab in svg)
model_tabs = self.get_model_tabs()
tabs = [tab.to_dict() for tab in model_tabs]
self.mainwindow.display_cnc_tabs(tabs)
class PyCutSimpleTableView(QtWidgets.QTableView):
""" """
def __init__(self, parent=None):
""" """
QtWidgets.QTableView.__init__(self, parent)
self.resizeColumnsToContents()
# Fixes the width of columns and the height of rows.
try:
# self.horizontalHeader().setResizeMode(QtWidgets.QHeaderView.Fixed)
# self.verticalHeader().setResizeMode(QtWidgets.QHeaderView.Fixed)
pass
except Exception:
pass # PySide
self.setAlternatingRowColors(True)
def setup(self):
"""
self.header = [
"x", # [0] float
"y", # [1] float
"radius", # [2] float
"enabled", # [3] checkbox
"del", # [4] button
]
"""
delegate = PyCutDoubleSpinBoxDelegate(self)
self.setItemDelegateForColumn(0, delegate)
delegate = PyCutDoubleSpinBoxDelegate(self)
self.setItemDelegateForColumn(1, delegate)
delegate = PyCutDoubleSpinBoxDelegate(self)
self.setItemDelegateForColumn(2, delegate)
delegate = PyCutCheckBoxDelegate(self)
self.setItemDelegateForColumn(3, delegate)
self.setup_persistent_editors()
def setup_persistent_editors(self):
""" """
# Make the combo boxes / check boxes / others specials always displayed.
for k in range(self.model().rowCount(None)):
self.openPersistentEditor(self.model().index(k, 0)) # x
self.openPersistentEditor(self.model().index(k, 1)) # y
self.openPersistentEditor(self.model().index(k, 2)) # radius
self.openPersistentEditor(self.model().index(k, 3)) # enabled
for row in range(self.model().rowCount(None)):
btn_del_tab = QtWidgets.QPushButton()
btn_del_tab.setText("")
btn_del_tab.setIcon(
QtGui.QIcon(":/images/tango/22x22/actions/edit-clear.png")
)
btn_del_tab.setToolTip("DeleteTab")
btn_del_tab.clicked.connect(self.cb_delete_tab)
self.setIndexWidget(self.model().index(row, 4), btn_del_tab)
# setup a right grid size
vwidth = self.verticalHeader().width()
hwidth = self.horizontalHeader().length()
swidth = self.style().pixelMetric(QtWidgets.QStyle.PM_ScrollBarExtent)
fwidth = self.frameWidth() * 2
# self.setFixedWidth(vwidth + hwidth + swidth + fwidth)
# self.setMinimumWidth(vwidth + hwidth + swidth + fwidth)
self.resizeColumnsToContents() # now!
self.setColumnWidth(0, 70) # x
self.setColumnWidth(1, 70) # y
self.setColumnWidth(2, 60) # radius quite small
def cb_delete_tab(self):
index = self.currentIndex()
idx = index.row()
# instruct the model to del an item
self.model().del_item(idx)
print("DEL")
for tab in self.model().tabs:
print(tab)
# inform main window (draw tab in svg)
model_tabs = self.model().tabs
tabs = [tab.to_dict() for tab in model_tabs]
self.parent().mainwindow.display_cnc_tabs(tabs)
def add_item(self, tab_data):
self.model().add_item(tab_data)
# do not make a "full" setup when adding a new item
self.setup_persistent_editors() # to show the editors on a new item
class PyCutSimpleTableModel(QtCore.QAbstractTableModel):
"""
model for the table view
"""
def __init__(self, tabs: List[Any], mainwindow):
super(PyCutSimpleTableModel, self).__init__()
self.tabs = tabs
self.mainwindow = mainwindow
self.header = [
"x", # [0] int
"y", # [1] int
"radius", # [2] int
"enabled", # [3] checkbox
"del", # [4] button
]
self.cnt = 0
def handleNewvalue(self, index: QtCore.QModelIndex, value: Any):
row = index.row()
col = index.column()
attrib = self.header[col]
# update pycut GUI
if attrib in ["x", "y", "radius", "enabled"]:
cnc_tab = self.tabs[row]
setattr(cnc_tab, attrib, value)
tabs = [tab.to_dict() for tab in self.tabs]
self.mainwindow.display_cnc_tabs(tabs)
def __str__(self):
self.cnt += 1
data = "--------------------------------\n"
for tab in self.tabs:
data += str(tab) + "\n"
return data
def dump(self):
self.cnt += 1
print("--------------------------------", self.cnt)
for tab in self.tabs:
print(tab)
def headerData(
self,
col: int,
orientation: QtCore.Qt.Orientation,
role: int = QtCore.Qt.ItemDataRole.EditRole,
) -> str | None:
if (
orientation == QtCore.Qt.Orientation.Horizontal
and role == QtCore.Qt.ItemDataRole.DisplayRole
):
return self.header[col]
return None
def rowCount(self, parent):
return len(self.tabs)
def columnCount(self, parent):
return len(self.header)
def setData(
self,
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
value,
role: int = QtCore.Qt.ItemDataRole.EditRole,
):
"""
for the cells without delegate
"""
tab = self.get_tab(index)
attr = self.get_tab_attr(index)
if role == QtCore.Qt.ItemDataRole.EditRole:
setattr(tab, attr, value)
def data(
self,
index: QtCore.QModelIndex | QtCore.QPersistentModelIndex,
role: int = QtCore.Qt.ItemDataRole.EditRole,
):
tab = self.get_tab(index)
attr = self.get_tab_attr(index)
# for check box, data is displayed in the "editor"
col = index.column()
if col == 4: # button
return None
# for checkboxes only
if col == 3: # checkbox
return None
if role == QtCore.Qt.ItemDataRole.DisplayRole:
val = getattr(tab, attr)
return val
if role == QtCore.Qt.ItemDataRole.EditRole:
val = getattr(tab, attr)
return val
return None
def flags(
self, index: QtCore.QModelIndex | QtCore.QPersistentModelIndex
) -> QtCore.Qt.ItemFlag:
flags = super(PyCutSimpleTableModel, self).flags(index)
flags |= QtCore.Qt.ItemFlag.ItemIsEditable
flags |= QtCore.Qt.ItemFlag.ItemIsSelectable
flags |= QtCore.Qt.ItemFlag.ItemIsEnabled
flags |= QtCore.Qt.ItemFlag.ItemIsDragEnabled
flags |= QtCore.Qt.ItemFlag.ItemIsDropEnabled
return flags
def add_item(self, tab_data):
tab = TabItem(tab_data)
idx = len(self.tabs)
self.beginInsertRows(QtCore.QModelIndex(), idx, idx)
self.tabs.append(tab)
self.endInsertRows()
def del_item(self, idx):
tab = self.tabs[idx]
self.beginRemoveRows(QtCore.QModelIndex(), idx, idx)
self.tabs.remove(tab)
self.endRemoveRows()
def swap_items(self, idx1, idx2):
self.beginResetModel()
self.tabs[idx1], self.tabs[idx2] = self.tabs[idx2], self.tabs[idx1]
self.endResetModel()
def get_tab(self, index):
return self.tabs[index.row()]
def get_tab_attr(self, index):
return self.header[index.column()]