forked from azagoruyko/rigBuilder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
widgets.py
1756 lines (1325 loc) · 58.6 KB
/
widgets.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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import sys
import os
import json
import math
from .utils import *
from .editor import *
from .jsonWidget import JsonWidget
DCC = os.getenv("RIG_BUILDER_DCC") or "maya"
if sys.version_info.major > 2:
RootPath = os.path.dirname(__file__) # Rig Builder root folder
else:
RootPath = os.path.dirname(__file__.decode(sys.getfilesystemencoding())) # legacy
if DCC == "maya":
import maya.cmds as cmds
class TemplateWidget(QFrame):
somethingChanged = Signal()
def __init__(self, *, executor=None, **kwargs):
super().__init__(**kwargs)
self.executor = executor or self._defaultExecutor # used to execute commands
def _defaultExecutor(self, cmd, env=None):
localEnv = dict(WidgetsAPI)
localEnv.update(env or {})
exec(cmd, localEnv)
return localEnv
def getDefaultData(self):
return self.getJsonData()
def getJsonData(self):
raise Exception("getJsonData must be implemented")
def setJsonData(self, data):
raise Exception("setJsonData must be implemented")
class EditTextDialog(QDialog):
saved = Signal(str) # emitted when user clicks OK
def __init__(self, text="", *, title="Edit", placeholder="", words=None, python=False):
super().__init__(parent=QApplication.activeWindow())
self.setWindowTitle(title)
self.setGeometry(0, 0, 600, 400)
layout = QVBoxLayout()
self.setLayout(layout)
if not python:
self.textWidget = QTextEdit()
self.textWidget.setTabStopWidth(16)
self.textWidget.setAcceptRichText(False)
self.textWidget.setWordWrapMode(QTextOption.NoWrap)
else:
self.textWidget = CodeEditorWidget()
self.textWidget.words = words or []
self.textWidget.setPlaceholderText(placeholder)
self.textWidget.setPlainText(text)
okBtn = QPushButton("OK")
okBtn.clicked.connect(self.saveAndClose)
layout.addWidget(self.textWidget)
layout.addWidget(okBtn)
centerWindow(self)
def saveAndClose(self):
self.saved.emit(self.textWidget.toPlainText())
self.accept()
class EditJsonDialog(QDialog):
saved = Signal(object)
def __init__(self, data, *, title="Edit"):
super().__init__(parent=QApplication.activeWindow())
self.setWindowTitle(title)
self.setGeometry(0, 0, 600, 400)
layout = QVBoxLayout()
self.setLayout(layout)
self.jsonWidget = JsonWidget(data)
okBtn = QPushButton("OK")
okBtn.clicked.connect(self.saveAndClose)
layout.addWidget(self.jsonWidget)
layout.addWidget(okBtn)
centerWindow(self)
def saveAndClose(self):
dataList = self.jsonWidget.toJsonList()
self.saved.emit(dataList)
self.accept()
class LabelTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._actualText = ""
layout = QVBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.label = QLabel()
self.label.setCursor(Qt.PointingHandCursor)
self.label.setWordWrap(True)
self.label.mouseDoubleClickEvent = self.labelDoubleClickEvent
layout.addWidget(self.label)
def setLabelText(self, text):
self._actualText = text
self.label.setText(self._actualText.replace("$ROOT", RootPath))
def labelDoubleClickEvent(self, event):
def save(text):
self.setLabelText(text)
self.somethingChanged.emit()
placeholder = '<img src="$ROOT/images/icons/info.png">Description'
editTextDialog = EditTextDialog(self._actualText, title="Edit text", placeholder=placeholder)
editTextDialog.saved.connect(save)
editTextDialog.show()
def getDefaultData(self):
return {"text": "Description", "default": "text"}
def getJsonData(self):
return {"text": self._actualText, "default": "text"}
def setJsonData(self, value):
self.setLabelText(value["text"])
class ButtonTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.buttonCommand = ""
layout = QHBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.buttonWidget = QPushButton("Press me")
self.buttonWidget.clicked.connect(self.buttonClicked)
self.buttonWidget.contextMenuEvent = self.buttonContextMenuEvent
layout.addWidget(self.buttonWidget)
def buttonContextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Edit label", self.editLabel)
menu.addAction("Edit command", self.editCommand)
menu.popup(event.globalPos())
def editLabel(self):
newName, ok = QInputDialog.getText(self, "Rename", "New label", QLineEdit.Normal, self.buttonWidget.text())
if ok:
self.buttonWidget.setText(newName)
self.somethingChanged.emit()
def editCommand(self):
def save(text):
self.buttonCommand = text
self.somethingChanged.emit()
words = list(self.executor("").keys())
editText = EditTextDialog(self.buttonCommand, title="Edit command", placeholder='chset("/someAttr", 1)', words=words, python=True)
editText.saved.connect(save)
editText.show()
def buttonClicked(self):
if self.buttonCommand:
def f():
self.executor(self.buttonCommand)
f()
def getDefaultData(self):
return {"command": 'chset("/someAttr", 1)',
"label": "Press me",
"default": "label"}
def getJsonData(self):
return {"command": self.buttonCommand,
"label": self.buttonWidget.text(),
"default": "label"}
def setJsonData(self, data):
self.buttonCommand = data["command"]
self.buttonWidget.setText(data["label"])
class CheckBoxTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
layout = QVBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.checkBox = QCheckBox()
self.checkBox.stateChanged.connect(lambda _=None: self.somethingChanged.emit())
layout.addWidget(self.checkBox)
def getJsonData(self):
return {"checked": self.checkBox.isChecked(), "default": "checked"}
def setJsonData(self, value):
with blockedWidgetContext(self.checkBox) as w:
w.setChecked(value["checked"])
class ComboBoxTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
layout = QVBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.comboBox = QComboBox()
self.comboBox.activated.connect(lambda _=None: self.somethingChanged.emit())
self.comboBox.contextMenuEvent = self.comboBoxContextMenuEvent
layout.addWidget(self.comboBox)
def comboBoxContextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Append", self.appendItem)
menu.addAction("Remove", self.removeItem)
menu.addAction("Edit", self.editItems)
menu.addSeparator()
menu.addAction("Clear", self.clearItems)
menu.popup(event.globalPos())
def editItems(self):
def save(newData):
self.setItems(newData)
data = self.getItems()
w = EditJsonDialog(data, title="Edit items")
w.saved.connect(save)
w.show()
def clearItems(self):
ok = QMessageBox.question(self, "Rig Builder", "Really clear all items?", QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes
if ok:
with blockedWidgetContext(self.comboBox) as w:
w.clear()
self.somethingChanged.emit()
def appendItem(self):
value, ok = QInputDialog.getText(self, "Rig Builder", "Value", QLineEdit.Normal, "")
if ok and value:
self.comboBox.addItem(value)
self.somethingChanged.emit()
def removeItem(self):
self.comboBox.removeItem(self.comboBox.currentIndex())
self.somethingChanged.emit()
def getItems(self):
return [smartConversion(self.comboBox.itemText(i)) for i in range(self.comboBox.count())]
def setItems(self, items):
with blockedWidgetContext(self.comboBox) as w:
w.clear()
for i, item in enumerate(items):
w.addItem(fromSmartConversion(item))
w.setItemData(i, jsonColor(item), Qt.ForegroundRole)
self.somethingChanged.emit()
def getDefaultData(self):
return {"items": ["a", "b"], "current": "a", "default": "current"}
def getJsonData(self):
return {"items": self.getItems(),
"current": smartConversion(self.comboBox.currentText()),
"default": "current"}
def setJsonData(self, value):
items = list(value["items"])
if value["current"] not in items:
items.append(value["current"]) # make sure current is in items
self.setItems(items)
with blockedWidgetContext(self.comboBox) as w:
w.setCurrentIndex(items.index(value["current"]))
class LineEditOptionsDialog(QDialog):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.setWindowTitle("Edit options")
layout = QVBoxLayout()
self.setLayout(layout)
formLayout = QFormLayout()
self.validatorWidget = QComboBox()
self.validatorWidget.addItems(["Default", "Int", "Double"])
self.validatorWidget.currentIndexChanged.connect(self.validatorIndexChanged)
self.minWidget = QLineEdit()
self.minWidget.setEnabled(False)
self.minWidget.setValidator(QIntValidator())
self.maxWidget = QLineEdit()
self.maxWidget.setEnabled(False)
self.maxWidget.setValidator(QIntValidator())
okBtn = QPushButton("OK")
okBtn.clicked.connect(self.accept)
okBtn.setAutoDefault(False)
formLayout.addRow("Validator", self.validatorWidget)
formLayout.addRow("Min", self.minWidget)
formLayout.addRow("Max", self.maxWidget)
layout.addLayout(formLayout)
layout.addWidget(okBtn)
def validatorIndexChanged(self, idx):
self.minWidget.setEnabled(idx!=0)
self.maxWidget.setEnabled(idx!=0)
class LineEditTemplateWidget(TemplateWidget):
defaultMin = 0
defaultMax = 100
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.optionsDialog = LineEditOptionsDialog(parent=self)
self.minValue = 0
self.maxValue = 100
self.validator = 0
self.value = ""
layout = QHBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.textWidget = QLineEdit()
self.textWidget.editingFinished.connect(self.textChanged)
self.textWidget.contextMenuEvent = self.textContextMenuEvent
self.sliderWidget = QSlider(Qt.Horizontal)
self.sliderWidget.setTracking(True)
self.sliderWidget.valueChanged.connect(self.sliderValueChanged)
self.sliderWidget.hide()
layout.addWidget(self.textWidget)
layout.addWidget(self.sliderWidget)
def colorizeValue(self):
color = jsonColor(self.value)
self.textWidget.setStyleSheet("QLineEdit {{ color: {} }}".format(color.name()))
def textChanged(self):
text = self.textWidget.text().strip()
if self.validator:
self.sliderWidget.setValue(float(text)*100)
self.value = smartConversion(text)
self.colorizeValue()
self.somethingChanged.emit()
def sliderValueChanged(self, v):
v /= 100.0
if self.validator == 1: # int
v = round(v)
self.value = v
self.textWidget.setText(str(v))
self.somethingChanged.emit()
def textContextMenuEvent(self, event):
menu = self.textWidget.createStandardContextMenu()
menu.addSeparator()
menu.addAction("Options...", self.optionsClicked)
menu.popup(event.globalPos())
def optionsClicked(self):
self.optionsDialog.minWidget.setText(str(self.minValue))
self.optionsDialog.maxWidget.setText(str(self.maxValue))
self.optionsDialog.validatorWidget.setCurrentIndex(self.validator)
self.optionsDialog.exec_()
self.minValue = int(self.optionsDialog.minWidget.text() or LineEditTemplateWidget.defaultMin)
self.maxValue = int(self.optionsDialog.maxWidget.text() or LineEditTemplateWidget.defaultMax)
self.validator = self.optionsDialog.validatorWidget.currentIndex()
self.setupSlider()
self.somethingChanged.emit()
def getJsonData(self):
return {"value": self.value,
"default": "value",
"min": self.minValue,
"max": self.maxValue,
"validator": self.validator}
def setupSlider(self):
if self.validator:
self.sliderWidget.show()
with blockedWidgetContext(self.sliderWidget) as slider:
if self.minValue:
slider.setMinimum(self.minValue*100) # slider values are int, so mult by 100
if self.maxValue:
slider.setMaximum(self.maxValue*100)
if self.value:
slider.setValue(float(self.value)*100)
else:
self.sliderWidget.hide()
def setJsonData(self, data):
self.validator = data.get("validator", 0)
self.minValue = int(data.get("min") or LineEditTemplateWidget.defaultMin)
self.maxValue = int(data.get("max") or LineEditTemplateWidget.defaultMax)
self.value = data.get("value", "")
if self.validator == 1: # int
validator = QIntValidator()
validator.setRange(self.minValue, self.maxValue)
self.textWidget.setValidator(validator)
elif self.validator == 2: # double
validator = QDoubleValidator()
validator.setRange(self.minValue, self.maxValue)
validator.setDecimals(2)
self.textWidget.setValidator(validator)
else:
self.textWidget.setValidator(None)
with blockedWidgetContext(self.textWidget) as w:
w.setText(fromSmartConversion(self.value))
self.setupSlider()
self.colorizeValue()
class LineEditAndButtonTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
defaultCmd = {"label": "<", "command": 'value = "Hello world!"'}
self.templates = {}
if DCC == "maya":
self.templates["Get selected"] = {"label": "<", "command":"import maya.cmds as cmds\nls = cmds.ls(sl=True)\nif ls: value = ls[0]"}
defaultCmd = self.templates["Get selected"]
self.templates["Get open file"] = {"label": "...", "command":'''from PySide2.QtWidgets import QFileDialog;import os
path,_ = QFileDialog.getOpenFileName(None, "Open file", os.path.expandvars(value))
value = path or value'''}
self.templates["Get save file"] = {"label": "...", "command":'''from PySide2.QtWidgets import QFileDialog;import os
path,_ = QFileDialog.getSaveFileName(None, "Save file", os.path.expandvars(value))
value = path or value'''}
self.templates["Get existing directory"] = {"label": "...", "command":'''from PySide2.QtWidgets import QFileDialog;import os
path = QFileDialog.getExistingDirectory(None, "Select directory", os.path.expandvars(value))
value = path or value'''}
self.buttonCommand = defaultCmd["command"]
self.value = ""
layout = QHBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.textWidget = QLineEdit()
self.textWidget.editingFinished.connect(self.textChanged)
self.buttonWidget = QPushButton(defaultCmd["label"])
self.buttonWidget.clicked.connect(self.buttonClicked)
self.buttonWidget.contextMenuEvent = self.buttonContextMenuEvent
layout.addWidget(self.textWidget)
layout.addWidget(self.buttonWidget)
def colorizeValue(self):
color = jsonColor(self.value)
self.textWidget.setStyleSheet("QLineEdit {{ color: {} }}".format(color.name()))
def textChanged(self):
self.value = smartConversion(self.textWidget.text().strip())
self.colorizeValue()
self.somethingChanged.emit()
def buttonContextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Edit label", self.editLabel)
menu.addAction("Edit command", self.editCommand)
if self.templates:
def setCommand(cmd):
self.buttonWidget.setText(cmd["label"])
self.buttonCommand = cmd["command"]
self.somethingChanged.emit()
templatesMenu = QMenu("Templates", self)
for k, cmd in self.templates.items():
templatesMenu.addAction(k, lambda cmd=cmd:setCommand(cmd))
menu.addMenu(templatesMenu)
menu.popup(event.globalPos())
def editLabel(self):
newName, ok = QInputDialog.getText(self, "Rename", "New label", QLineEdit.Normal, self.buttonWidget.text())
if ok:
self.buttonWidget.setText(newName)
self.somethingChanged.emit()
def editCommand(self):
def save(text):
self.buttonCommand = text
self.somethingChanged.emit()
words = list(self.executor("").keys())
editText = EditTextDialog(self.buttonCommand, title="Edit command", placeholder="Your python command...", words=words, python=True)
editText.saved.connect(save)
editText.show()
def buttonClicked(self):
if self.buttonCommand:
def f():
env = {"value": smartConversion(self.textWidget.text().strip())}
outEnv = self.executor(self.buttonCommand, env)
self.value = outEnv["value"]
self.textWidget.setText(fromSmartConversion(self.value))
self.somethingChanged.emit()
f()
def getJsonData(self):
return {"value": self.value,
"buttonCommand": self.buttonCommand,
"buttonLabel": self.buttonWidget.text(),
"default": "value"}
def setJsonData(self, data):
self.value = data["value"]
with blockedWidgetContext(self.textWidget) as w:
w.setText(fromSmartConversion(self.value))
self.buttonCommand = data["buttonCommand"]
self.buttonWidget.setText(data["buttonLabel"])
self.colorizeValue()
class ListBoxItem(QListWidgetItem):
ValueRole = Qt.UserRole + 1
def __init__(self, value):
super().__init__()
self._value = value
self.setFlags(self.flags() | Qt.ItemIsEditable)
def clone(self):
return ListBoxItem(copyJson(self._value))
def data(self, role):
if role == Qt.ForegroundRole:
return jsonColor(self._value)
elif role == Qt.DisplayRole:
return fromSmartConversion(self._value)
elif role == Qt.EditRole:
return fromSmartConversion(self._value) # always edit as string
elif role == ListBoxItem.ValueRole:
return self._value
return super().data(role)
def setData(self, role, value):
if role == Qt.EditRole:
self._value = smartConversion(value)
elif role == ListBoxItem.ValueRole:
self._value = value
super().setData(role, value)
class ListBoxTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
layout = QVBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.listWidget = QListWidget()
self.listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.listWidget.itemSelectionChanged.connect(self.somethingChanged.emit)
self.listWidget.itemChanged.connect(self.itemChanged)
self.listWidget.contextMenuEvent = self.listContextMenuEvent
layout.addWidget(self.listWidget, alignment=Qt.AlignLeft|Qt.AlignTop)
def listContextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Append", self.appendItem)
menu.addAction("Remove", self.removeItem)
menu.addAction("Edit", self.editItems)
def f():
self.listWidget.sortItems()
self.somethingChanged.emit()
menu.addAction("Sort", f)
menu.addSeparator()
if DCC in ["maya"]:
dccLabel = DCC.capitalize()
menu.addAction("Get selected from "+dccLabel, Callback(self.getFromDCC, False))
menu.addAction("Add selected from "+dccLabel, Callback(self.getFromDCC, True))
menu.addAction("Select in "+dccLabel, Callback(self.selectInDCC, False))
menu.addAction("Select all in "+dccLabel, self.selectInDCC)
menu.addSeparator()
menu.addAction("Clear", self.clearItems)
menu.popup(event.globalPos())
def itemChanged(self, item):
self.listWidget.closePersistentEditor(item)
self.somethingChanged.emit()
self.resizeWidget()
def editItems(self):
def save(newData):
self.setItems(newData)
self.resizeWidget()
data = self.getItems()
w = EditJsonDialog(data, title="Edit items")
w.saved.connect(save)
w.show()
def resizeWidget(self):
width = self.listWidget.sizeHintForColumn(0) + 50
height = 0
for i in range(self.listWidget.count()):
height += self.listWidget.sizeHintForRow(i)
height += 2*self.listWidget.frameWidth() + 50
self.listWidget.setFixedSize(clamp(width, 100, 500), clamp(height, 100, 500))
def selectInDCC(self, allItems=True):
items = [self.listWidget.item(i).text() for i in range(self.listWidget.count()) if allItems or self.listWidget.item(i).isSelected()]
if DCC == "maya":
cmds.select(items)
def getFromDCC(self, add=False):
def updateUI(nodes):
if not add:
with blockedWidgetContext(self.listWidget) as w:
w.clear()
for n in nodes:
self.listWidget.addItem(ListBoxItem(n))
self.resizeWidget()
self.somethingChanged.emit()
if DCC == "maya":
nodes = [n for n in cmds.ls(sl=True)]
updateUI(nodes)
def clearItems(self):
ok = QMessageBox.question(self, "Rig Builder", "Really clear all items?", QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes
if ok:
with blockedWidgetContext(self.listWidget) as w:
w.clear()
self.somethingChanged.emit()
self.resizeWidget()
def appendItem(self):
text = "item%d"%(self.listWidget.count()+1)
self.listWidget.addItem(ListBoxItem(text))
self.resizeWidget()
self.somethingChanged.emit()
def removeItem(self):
for item in self.listWidget.selectedItems():
self.listWidget.takeItem(self.listWidget.row(item))
self.resizeWidget()
self.somethingChanged.emit()
def getItems(self):
return [self.listWidget.item(i).data(ListBoxItem.ValueRole) for i in range(self.listWidget.count())]
def setItems(self, items):
with blockedWidgetContext(self.listWidget) as w:
w.clear()
for v in items:
w.addItem(ListBoxItem(v))
self.somethingChanged.emit()
def getDefaultData(self):
return {"items": ["a", "b"], "current":0, "selected":[], "default": "items"}
def getJsonData(self):
return {"items": self.getItems(),
"selected": [self.listWidget.row(item) for item in self.listWidget.selectedItems()],
"default": "items"}
def setJsonData(self, value):
self.setItems(value["items"])
with blockedWidgetContext(self.listWidget) as w:
for i in value.get("selected", []):
item = w.item(i)
if item:
item.setSelected(True)
self.resizeWidget()
class RadioButtonTemplateWidget(TemplateWidget):
Columns = [2,3,4,5]
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.numColumns = 3
layout = QGridLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.buttonsGroupWidget = QButtonGroup()
self.buttonsGroupWidget.buttonClicked.connect(self.buttonClicked)
def contextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Edit", self.editClicked)
menu.addSeparator()
columnsMenu = QMenu("Columns", self)
for n in RadioButtonTemplateWidget.Columns:
action = columnsMenu.addAction(str(n) + " columns", Callback(self.setColumns, n))
if n == self.numColumns:
action.setCheckable(True)
action.setChecked(True)
menu.addMenu(columnsMenu)
menu.popup(event.globalPos())
def setColumns(self, n):
data = self.getJsonData()
data["columns"] = n
self.setJsonData(data)
self.somethingChanged.emit()
def colorizeButtons(self):
for b in self.buttonsGroupWidget.buttons():
b.setStyleSheet("QRadioButton {background-color: #2a6931}" if b.isChecked() else "")
def buttonClicked(self, b):
self.colorizeButtons()
self.somethingChanged.emit()
def clearButtons(self):
clearLayout(self.layout())
for b in self.buttonsGroupWidget.buttons():
self.buttonsGroupWidget.removeButton(b)
def editClicked(self):
items = ";".join([b.text() for b in self.buttonsGroupWidget.buttons()])
newItems, ok = QInputDialog.getText(self, "Rig Builder", "Items separated with ';'", QLineEdit.Normal, items)
if ok and newItems:
data = self.getJsonData()
data["items"] = [x.strip() for x in newItems.split(";")]
self.setJsonData(data)
self.somethingChanged.emit()
def getDefaultData(self):
return {"items": ["Helpers", "Run"], "current": 0, "default": "current", "columns": self.numColumns}
def getJsonData(self):
return {"items": [b.text() for b in self.buttonsGroupWidget.buttons()],
"current": self.buttonsGroupWidget.checkedId(),
"columns": self.numColumns,
"default": "current"}
def setJsonData(self, value):
gridLayout = self.layout()
self.clearButtons()
self.numColumns = value["columns"]
gridLayout.setDefaultPositioning(self.numColumns, Qt.Horizontal)
for i, item in enumerate(value["items"]):
button = QRadioButton(item)
gridLayout.addWidget(button, i//self.numColumns, i%self.numColumns)
self.buttonsGroupWidget.addButton(button)
self.buttonsGroupWidget.setId(button, i)
if value["current"] not in range(len(value["items"])):
value["current"] = 0
with blockedWidgetContext(self.buttonsGroupWidget) as w:
w.buttons()[value["current"]].setChecked(True)
self.colorizeButtons()
class TableTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
layout = QVBoxLayout()
self.setLayout(layout)
layout.setContentsMargins(QMargins())
self.tableWidget = QTableWidget()
self.tableWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
self.tableWidget.verticalHeader().setSectionsMovable(True)
self.tableWidget.verticalHeader().sectionMoved.connect(self.sectionMoved)
self.tableWidget.horizontalHeader().setSectionsMovable(True)
self.tableWidget.horizontalHeader().sectionMoved.connect(self.sectionMoved)
self.tableWidget.contextMenuEvent = self.tableContextMenuEvent
self.tableWidget.itemChanged.connect(self.tableItemChanged)
header = self.tableWidget.horizontalHeader()
if "setResizeMode" in dir(header):
header.setResizeMode(QHeaderView.ResizeToContents)
elif "setSectionResizeMode" in dir(header):
header.setSectionResizeMode(QHeaderView.ResizeToContents)
self.tableWidget.horizontalHeader().sectionDoubleClicked.connect(self.sectionDoubleClicked)
layout.addWidget(self.tableWidget)
def sectionMoved(self, idx, oldIndex, newIndex):
self.somethingChanged.emit()
def tableItemChanged(self, item):
item.setForeground(jsonColor(smartConversion(item.text())))
self.somethingChanged.emit()
def sectionDoubleClicked(self, column):
newName, ok = QInputDialog.getText(self, "Rename", "New name", QLineEdit.Normal, self.tableWidget.horizontalHeaderItem(column).text())
if ok:
self.tableWidget.horizontalHeaderItem(column).setText(newName)
self.somethingChanged.emit()
def tableContextMenuEvent(self, event):
menu = QMenu(self)
menu.addAction("Duplicate", self.duplicateRow)
menu.addSeparator()
rowMenu = QMenu("Row", self)
rowMenu.addAction("Insert", Callback(self.insertRow, self.tableWidget.currentRow()))
rowMenu.addAction("Append", Callback(self.insertRow, self.tableWidget.currentRow()+1))
rowMenu.addSeparator()
def f():
for item in self.tableWidget.selectedItems():
self.tableWidget.removeRow(self.tableWidget.row(item))
self.resizeWidget()
self.somethingChanged.emit()
rowMenu.addAction("Remove", f)
menu.addMenu(rowMenu)
columnMenu = QMenu("Column", self)
columnMenu.addAction("Insert", Callback(self.insertColumn, self.tableWidget.currentColumn()))
columnMenu.addAction("Append", Callback(self.insertColumn, self.tableWidget.currentColumn()+1))
columnMenu.addSeparator()
def f():
for item in self.tableWidget.selectedItems():
self.tableWidget.removeColumn(self.tableWidget.column(item))
self.resizeWidget()
self.somethingChanged.emit()
columnMenu.addAction("Remove", f)
menu.addMenu(columnMenu)
menu.addSeparator()
menu.addAction("Clear", self.clearAll)
menu.popup(event.globalPos())
def resizeWidget(self):
height = 0
for i in range(self.tableWidget.rowCount()):
height += self.tableWidget.rowHeight(i)
headerHeight = self.tableWidget.verticalHeader().sizeHint().height()
height += headerHeight*2
self.tableWidget.setFixedHeight(clamp(height, headerHeight+100, 500))
def clearAll(self):
ok = QMessageBox.question(self, "Rig Builder", "Really remove all items?", QMessageBox.Yes and QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes
if ok:
self.tableWidget.clearContents()
self.tableWidget.setRowCount(1)
self.resizeWidget()
self.somethingChanged.emit()
def insertColumn(self, current):
self.tableWidget.insertColumn(current)
self.tableWidget.setHorizontalHeaderItem(current, QTableWidgetItem("Untitled"))
for r in range(self.tableWidget.rowCount()):
self.tableWidget.setItem(r, current, QTableWidgetItem())
self.resizeWidget()
def insertRow(self, current):
self.tableWidget.insertRow(current)
for c in range(self.tableWidget.columnCount()):
self.tableWidget.setItem(current, c, QTableWidgetItem())
self.resizeWidget()
def duplicateRow(self):
newRow = self.tableWidget.currentRow()+1
prevRow = self.tableWidget.currentRow()
self.tableWidget.insertRow(newRow)
for c in range(self.tableWidget.columnCount()):
prevItem = self.tableWidget.item(prevRow, c)
self.tableWidget.setItem(newRow, c, prevItem.clone() if prevItem else QTableWidgetItem())
self.resizeWidget()
def getDefaultData(self):
return {"items": [("a", "1")], "header": ["name", "value"], "default": "items"}
def getJsonData(self):
sortedColumns = sorted([c for c in range(self.tableWidget.columnCount())], key=lambda c: self.tableWidget.visualColumn(c))
header = [self.tableWidget.horizontalHeaderItem(c).text() for c in sortedColumns]
vheader = self.tableWidget.verticalHeader()
hheader = self.tableWidget.horizontalHeader()
items = []
for r in range(self.tableWidget.rowCount()):
row = []
for c in range(self.tableWidget.columnCount()):
item = self.tableWidget.item(vheader.logicalIndex(r), hheader.logicalIndex(c))
row.append(smartConversion(item.text()) if item else "")
items.append(row)
return {"items": items, "header": header, "default": "items"}
def setJsonData(self, value):
self.tableWidget.setColumnCount(len(value["header"]))
self.tableWidget.setHorizontalHeaderLabels(value["header"])
items = value["items"]
self.tableWidget.setRowCount(len(items))
for r, row in enumerate(items):
for c, data in enumerate(row):
item = QTableWidgetItem(fromSmartConversion(data))
item.setForeground(jsonColor(data))
self.tableWidget.setItem(r, c, item)
self.tableWidget.resizeRowsToContents()
self.resizeWidget()
class TextTemplateWidget(TemplateWidget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
layout = QVBoxLayout()
self.setLayout(layout)