-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib.py
1311 lines (954 loc) · 38.7 KB
/
lib.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 functools import partial
import json
import logging
import os
import pprint
import sys
from coconodz import (Qt,
application
)
LOG = logging.getLogger(name="CocoNodz.nodegraph")
class SafeOpen(object):
""" safer handler to open files
"""
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.f = None
def __enter__(self):
try:
self.f = open(*self.args, **self.kwargs)
return self.f
except:
raise IOError('Could not open %s' % self.args)
def __exit__(self, *exc_info):
if self.f:
self.f.close()
class BaseWindow(Qt.QtWidgets.QMainWindow):
""" Sets up a simple Base window
"""
TITLE = "CocoNodz Nodegraph"
PALETTE_PATH = os.path.join(os.path.dirname(__file__), "palette.config")
def __init__(self, parent):
super(BaseWindow, self).__init__(parent)
# apply the color palette
set_application_palette(self.PALETTE_PATH, application)
self.__parent = parent
self._setup_ui()
@property
def central_widget(self):
""" gets the set central widget
Returns: QWidget
"""
return self._central_widget
@property
def central_layout(self):
""" gets the set central layout
Returns: QVBoxLayout
"""
return self._central_layout
def _setup_ui(self):
""" creates all widgets and actions and connects signals
Returns:
"""
self._central_widget = Qt.QtWidgets.QWidget(self.__parent)
self._central_layout = Qt.QtWidgets.QVBoxLayout()
self.setWindowTitle(self.TITLE)
self.setCentralWidget(self.central_widget)
if not os.name == 'nt':
self.setWindowFlags(Qt.QtCore.Qt.Tool)
self.central_widget.setLayout(self.central_layout)
class ContextWidget(Qt.QtWidgets.QMenu):
""" global context widget
The context widget is the main class and it should be accessed in the nodegraph
when pressing a mousebutton or key.
For the moment we will use the QMenu for that, but the long running goal is to
have a proper hotbox widget we can mixin or inherit from
"""
signal_available_items_changed = Qt.QtCore.Signal()
signal_opened = Qt.QtCore.Signal()
def __init__(self, parent):
super(ContextWidget, self).__init__(parent)
self._items = None
self._context = None
self._expect_msg = "Expected type {0}, got {1} instead"
self.initial_pos = None
@property
def available_items(self):
""" available items dictionary
This will dependent on the subclass and can be anything like QActions, QButtons, list.
We choose as dictionary as base, because it will be the most flexible approach
Returns: dict
"""
return self._items
@available_items.setter
def available_items(self, items_dict):
self._items = items_dict
self.signal_available_items_changed.emit()
@property
def context(self):
""" holds the "real" context widget
Returns: QWidget instance
"""
return self._context
@context.setter
def context(self, context_widget):
""" sets the "real" context widget
Args:
context_widget: QWidget instance
Returns:
"""
self._context = context_widget
self._update_context()
def _update_context(self):
""" clears the underlying menu and replaces the default widget with set context
Returns:
"""
self.clear()
action = Qt.QtWidgets.QWidgetAction(self)
action.setDefaultWidget(self.context)
self.addAction(action)
def setup_ui(self):
""" connect overall signals
Returns:
"""
self.signal_available_items_changed.connect(self.on_available_items_changed)
def open(self, at_initial=False):
""" opens widget on cursor position
Returns:
"""
self.signal_opened.emit()
if not at_initial:
pos = Qt.QtGui.QCursor.pos()
self.initial_pos = pos
else:
pos = self.initial_pos
assert isinstance(pos, Qt.QtCore.QPoint)
self.move(pos.x(), pos.y())
self.exec_()
class GraphContext(ContextWidget):
def __init__(self, parent):
super(GraphContext, self).__init__(parent)
# defining items as empty list, because we want to loop trough
# in the setup_ui method
self.available_items = list()
self.setup_ui()
def add_button(self, button):
""" allows the addition of QPushButton instances to main layout only
Args:
button:
Returns:
"""
assert isinstance(button, Qt.QtWidgets.QPushButton), \
self._expect_msg.format(Qt.QtWidgets.QPushButton, type(button))
self.central_layout.addWidget(button)
LOG.info("Added button {0}".format(button))
def setup_ui(self):
super(GraphContext, self).setup_ui()
widget = Qt.QtWidgets.QWidget(self)
layout = Qt.QtWidgets.QVBoxLayout(widget)
for button in self.available_items:
layout.addWidget(button)
self.context = widget
def on_available_items_changed(self):
""" actions that should run if items have changed
Returns:
"""
self.setup_ui()
class BackdropContext(ContextWidget):
def __init__(self, parent):
super(BackdropContext, self).__init__(parent)
self._color_dialog = Qt.QtWidgets.QColorDialog()
self._color_dialog.setOptions(Qt.QtWidgets.QColorDialog.ShowAlphaChannel)
self._color_dialog.finished.connect(self.open)
self._color_dialog.currentColorChanged.connect(self.on_color_changed)
self._desctiption_text = ""
self._description_font_size = 10
self._color = None
self._border_color = None
self._backdrop_item = None
self.setup_ui()
@property
def backdrop_item(self):
return self._backdrop_item
@backdrop_item.setter
def backdrop_item(self, backdrop_item):
assert isinstance(backdrop_item, Backdrop), \
"Expected '{}' instance as backdrop item got '{}'".format(type(Backdrop), type(backdrop_item))
self._backdrop_item = backdrop_item
def _set_button_color(self, button, color):
button.setStyleSheet("QToolButton {background-color: rgba(%s, %s, %s, %s);}" % (color[0],
color[1],
color[2],
color[3]))
button.setProperty("color", color)
def _open_color_dialog(self, button):
color = button.property("color")
self._color_dialog.setCurrentColor(Qt.QtGui.QColor(*color))
self._color_dialog.setProperty("color_type", button.property("color_type"))
self._color_dialog.show()
def setup_ui(self):
widget = Qt.QtWidgets.QWidget(self)
layout = Qt.QtWidgets.QVBoxLayout(widget)
group = Qt.QtWidgets.QGroupBox("Edit Backdrop")
group_layout = Qt.QtWidgets.QVBoxLayout()
group.setLayout(group_layout)
layout.addWidget(group)
description_group = Qt.QtWidgets.QGroupBox("Description")
description_layout = Qt.QtWidgets.QHBoxLayout()
description_group.setLayout(description_layout)
description_field = Qt.QtWidgets.QTextEdit("test text")
description_layout.addWidget(description_field)
group_layout.addWidget(description_group)
appearance_group = Qt.QtWidgets.QGroupBox("Appearance")
appearance_layout = Qt.QtWidgets.QGridLayout()
appearance_group.setLayout(appearance_layout)
group_layout.addWidget(appearance_group)
title_font_label = Qt.QtWidgets.QLabel("Title font size:")
appearance_layout.addWidget(title_font_label, 0, 0)
title_fonz_size = Qt.QtWidgets.QSpinBox()
appearance_layout.addWidget(title_fonz_size, 0, 1)
description_font_label = Qt.QtWidgets.QLabel("Description fonz size:")
appearance_layout.addWidget(description_font_label, 1, 0)
description_font_size = Qt.QtWidgets.QSpinBox()
appearance_layout.addWidget(description_font_size, 1, 1)
backdrop_color_label = Qt.QtWidgets.QLabel("Color:")
appearance_layout.addWidget(backdrop_color_label, 2, 0)
backdrop_color = Qt.QtWidgets.QToolButton()
backdrop_color.setProperty("color_type", "color")
appearance_layout.addWidget(backdrop_color, 2, 1)
backdrop_border_color_label = Qt.QtWidgets.QLabel("Border color:")
appearance_layout.addWidget(backdrop_border_color_label, 3, 0)
backdrop_border_color = Qt.QtWidgets.QToolButton()
backdrop_border_color.setProperty("color_type", "border_color")
appearance_layout.addWidget(backdrop_border_color, 3, 1)
self.context = widget
# adjust content
if self.backdrop_item:
self._set_button_color(backdrop_color, self.backdrop_item.color)
self._set_button_color(backdrop_border_color, self.backdrop_item.border_color)
description_field.setPlainText(self.backdrop_item.description_text)
description_font_size.setValue(self.backdrop_item.description_font_size)
title_fonz_size.setValue(self.backdrop_item.title_font_size)
backdrop_color.clicked.connect(partial(self._open_color_dialog, backdrop_color))
backdrop_border_color.clicked.connect(partial(self._open_color_dialog, backdrop_border_color))
# connect signals
description_field.textChanged.connect(partial(self.on_description_text_changed,
description_field)
)
description_font_size.valueChanged.connect(self.on_description_font_size_changed)
title_fonz_size.valueChanged.connect(self.on_title_font_size_changed)
def on_description_text_changed(self, description_widget, *args):
self.backdrop_item.description_text = description_widget.toPlainText()
def on_color_changed(self, color):
if self.backdrop_item:
if self._color_dialog.property("color_type") == "color":
self.backdrop_item.color = color
elif self._color_dialog.property("color_type") == "border_color":
self.backdrop_item.border_color = color
def on_title_font_size_changed(self, value):
self.backdrop_item.title_font_size = value
def on_description_font_size_changed(self, value):
self.backdrop_item.description_font_size = value
def open(self, at_initial=False):
self.setup_ui()
super(BackdropContext, self).open(at_initial)
class AttributeContext(ContextWidget):
""" simple tree view widget we will use to display node attributes in nodegraph
"""
signal_input_accepted = Qt.QtCore.Signal(str, str)
def __init__(self, parent, mode=""):
super(AttributeContext, self).__init__(parent)
# defining items as empty list, because we want to pass dictionary-like data
# within the tree widget in the setup_ui method
self.available_items = dict()
self._mode = mode
self._tree_widget = None
self._mask_widget = None
self._column = 0
self.setup_ui()
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, value):
assert isinstance(value, basestring), self._expect_msg.format("string", type(value))
self._mode = value
@property
def tree_widget(self):
return self._tree_widget
@tree_widget.setter
def tree_widget(self, tree_widget):
self._tree_widget = tree_widget
@property
def mask_widget(self):
return self._mask_widget
@mask_widget.setter
def mask_widget(self, line_edit_widget):
self._mask_widget = line_edit_widget
def _populate_tree(self, tree_widget):
""" based on the dictionary data this will add all the items
Args:
tree_widget: QTreeWidget
Returns:
"""
tree_items = []
# recursive items addition
def _add_items(parent, data):
for key, value in data.iteritems():
tree_item = Qt.QtWidgets.QTreeWidgetItem(parent)
tree_item.setText(0, key)
tree_widget.addTopLevelItem(tree_item)
tree_items.append(tree_item)
if value:
if isinstance(value, (basestring, int, float, bool)):
value = list([value])
if isinstance(value, (list, tuple)):
for member in value:
child = Qt.QtWidgets.QTreeWidgetItem(tree_item)
child.setText(0, member)
tree_item.addChild(child)
tree_items.append(child)
if isinstance(value, dict):
if not isinstance(parent, Qt.QtWidgets.QTreeWidget):
parent.addChild(tree_item)
else:
_add_items(tree_item, value)
# add all items
_add_items(tree_widget, self.available_items)
def setup_ui(self):
""" sets up the context and connects all signals
Returns:
"""
super(AttributeContext, self).setup_ui()
widget = Qt.QtWidgets.QWidget(self)
filter_layout = Qt.QtWidgets.QHBoxLayout()
label = Qt.QtWidgets.QLabel("Filter:")
mask = Qt.QtWidgets.QLineEdit()
filter_layout.addWidget(label)
filter_layout.addWidget(mask)
layout = Qt.QtWidgets.QVBoxLayout(widget)
layout.addLayout(filter_layout)
tree = Qt.QtWidgets.QTreeWidget()
tree.setColumnCount(self._column + 1)
tree.setHeaderLabels([self.mode])
tree.sortItems(self._column, Qt.QtCore.Qt.AscendingOrder)
layout.addWidget(tree)
self._populate_tree(tree)
tree.doubleClicked.connect(self.on_tree_double_clicked)
mask.textChanged.connect(self.on_filter_changed)
self.context = widget
self.tree_widget = tree
self.mask_widget = mask
def on_available_items_changed(self):
""" should rebuild the context when available items changed
Returns:
"""
self.setup_ui()
def on_tree_double_clicked(self, index):
""" defines what will happen when the tree was double-clicked
Args:
index:
Returns:
"""
if self.tree_widget:
self.signal_input_accepted.emit(self.property("node_name"),
self.tree_widget.itemFromIndex(index).text(self._column))
def on_filter_changed(self):
""" look for item text matches based on the filter string and display only matched items
Returns:
"""
# couldn't find an easy way to get a list of currently
# displayed items, therefore this implementations has to hide all items first
# looking for string matched on all items
# and unhide all matched items and all their parents recursively
# recursively enabling item visibilities upstream
def _unhide_parent(item):
item.setHidden(False)
if item.parent():
_unhide_parent(item.parent())
iterator = Qt.QtWidgets.QTreeWidgetItemIterator(self.tree_widget, Qt.QtWidgets.QTreeWidgetItemIterator.All)
while iterator.value():
iterator.value().setHidden(True)
iterator += 1
# look for matches and show them
input_string = str(self.mask_widget.text())
if input_string != "":
matched_items = self.tree_widget.findItems(input_string,
(Qt.QtCore.Qt.MatchContains | Qt.QtCore.Qt.MatchRecursive | Qt.QtCore.Qt.MatchCaseSensitive))
for item in matched_items:
_unhide_parent(item)
else:
# unfortunately an empty string returns a match for all items
# in this case we will show all items again
iterator = Qt.QtWidgets.QTreeWidgetItemIterator(self.tree_widget, Qt.QtWidgets.QTreeWidgetItemIterator.All)
while iterator.value():
iterator.value().setHidden(False)
iterator += 1
class SearchField(ContextWidget):
""" simple SearchField Widget we will use so search for nodes in the nodegraph
"""
signal_input_accepted = Qt.QtCore.Signal(str)
def __init__(self, parent):
super(SearchField, self).__init__(parent)
self._items = []
self.setup_ui()
def _setup_completer(self, line_edit_widget):
""" creates a QCompleter and sets it to the given widget
Args:
line_edit_widget: QLineEdit
Returns:
"""
completer = Qt.QtWidgets.QCompleter(self.available_items)
completer.setCompletionMode(Qt.QtWidgets.QCompleter.PopupCompletion)
completer.setCaseSensitivity(Qt.QtCore.Qt.CaseInsensitive)
line_edit_widget.setCompleter(completer)
def setup_ui(self):
""" extends the setup ui method
This should create the base widgets and connect signals
"""
super(SearchField, self).setup_ui()
# set search field
self.mask = Qt.QtWidgets.QLineEdit(self)
self.context = self.mask
self.mask.setFocus()
self.mask.returnPressed.connect(self.on_accept)
def on_accept(self):
""" sends signal if input is one of the available items
Returns:
"""
search_input = str(self.mask.text())
if search_input in self.available_items:
self.signal_input_accepted.emit(search_input)
self.close()
def on_available_items_changed(self):
""" actions that should run if items have changed
Returns:
"""
self._setup_completer(self.mask)
class RenameField(ContextWidget):
""" simeple RenameField widget we will use in Nodegraph
"""
signal_input_accepted = Qt.QtCore.Signal(str)
VALIDATION_REGEX = "[A-Za-z0-9_]+"
def __init__(self, parent):
super(RenameField, self).__init__(parent)
self._items = []
self._validation_regex = self.VALIDATION_REGEX
self.setup_ui()
@property
def validation_regex(self):
""" holds the current regular expression pattern
Returns:
"""
return self._validation_regex
@validation_regex.setter
def validation_regex(self, regex_str):
""" sets the validation regex that will be used in the mask
Args:
regex_str: string that holds the regular expression pattern
Returns:
"""
assert isinstance(regex_str, basestring)
self._validation_regex = regex_str
self.setup_ui()
def setup_ui(self):
""" create base widgets and connection internal signals
Returns:
"""
self.mask = Qt.QtWidgets.QLineEdit(self)
self.mask.setValidator( Qt.QtGui.QRegExpValidator(Qt.QtCore.QRegExp(self.validation_regex)))
self.context = self.mask
self.mask.setFocus()
self.mask.returnPressed.connect(self.on_accept)
def on_accept(self):
""" sends signal if input is accepted
Returns:
"""
rename_input = str(self.mask.text())
self.signal_input_accepted.emit(rename_input)
self.close()
class Backdrop(Qt.QtWidgets.QGraphicsRectItem):
""" Rectangle Item that visually groups nodes insides its bounds
"""
def __init__(self, name, **kwargs):
"""
Args:
name: name of the backdrop that will be displayed as title
bounds: tuple including x,y of the topleft corner width and height
color: tuple including RGBA as integers from 0-255
border_color: tuple including RGBA as integers from 0-255
"""
super(Backdrop, self).__init__()
self.name = name
self._bounds = kwargs.setdefault("bounds", [0, 0, 300, 300])
self._color = kwargs.setdefault("color", [255, 0, 0, 50])
self._font = kwargs.setdefault("font", "Arial")
self._border_color = kwargs.setdefault("border_color", [255, 255, 255, 50])
self._description_text = kwargs.setdefault("description", "")
self._title_font_size = kwargs.setdefault("title_font_size", 12)
self._description_font_size = kwargs.setdefault("description_font_size", 12)
# use bounds as tuple or list
self.setRect(*self._bounds)
self._bounds = list(self._bounds)
self._handle_size = 20
self._minimum_width = 100
self._resize_space = 25
self._title_space = 5
self._selection = []
self._handle_in_use = False
# flags
self.setAcceptHoverEvents(True)
self.setFlag(Qt.QtWidgets.QGraphicsItem.ItemIsMovable)
self.setFlag(Qt.QtWidgets.QGraphicsItem.ItemIsSelectable)
self.setFlag(Qt.QtWidgets.QGraphicsItem.ItemIsFocusable, True)
# style
self._bg_color = Qt.QtGui.QColor(*self._color)
self._bg_border_color = Qt.QtGui.QColor(*self._border_color)
self._bg_brush = Qt.QtGui.QBrush(self._bg_color, Qt.QtCore.Qt.SolidPattern)
self._bg_pen = Qt.QtGui.QPen(Qt.QtCore.Qt.SolidLine)
self._bg_pen.setJoinStyle(Qt.QtCore.Qt.RoundJoin)
self._bg_pen.setWidth(1)
self._bg_pen.setColor(self._bg_border_color)
self._bg_pen_selected = self._bg_pen
self._bg_pen_selected.setWidth(2)
self._handle_brush = Qt.QtGui.QBrush(self._bg_color, Qt.QtCore.Qt.BDiagPattern)
self._title_font = Qt.QtGui.QFont(self._font, self.title_font_size)
self._title_font.setBold(True)
self._description_font = Qt.QtGui.QFont(self._font, self.description_font_size)
self.background = None
self.title_bar = None
self.title = None
self.handle = None
self.setup_ui()
self.description_text = self._description_text
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def description_text(self):
return self._description_text
@description_text.setter
def description_text(self, text):
self._adjust_description(text)
self._description_text = text
@property
def title_font_size(self):
return self._title_font_size
@title_font_size.setter
def title_font_size(self, size):
assert isinstance(size, int)
self._title_font_size = size
self._title_font.setPointSize(size)
self.title.setFont(self._title_font)
self.adjust_to_minimum_height()
@property
def description_font_size(self):
return self._description_font_size
@description_font_size.setter
def description_font_size(self, size):
assert isinstance(size, int)
self._description_font_size = size
self._description_font.setPointSize(size)
self.description.setFont(self._description_font)
self._adjust_description(self.description_text)
@property
def color(self):
return self._color
@color.setter
def color(self, color):
assert isinstance(color, Qt.QtGui.QColor)
self._bg_brush.setColor(color)
self._handle_brush.setColor(color)
self.setBrush(self._bg_brush)
self.title_bar.setBrush(self._bg_brush)
self._color = [color.red(), color.green(), color.blue(), color.alpha()]
@property
def border_color(self):
return self._border_color
@border_color.setter
def border_color(self, color):
assert isinstance(color, Qt.QtGui.QColor)
self._bg_pen.setColor(color)
self.setPen(self._bg_pen)
self.handle.setPen(self._bg_pen)
self.title_bar.setPen(self._bg_pen)
self._border_color = [color.red(), color.green(), color.blue(), color.alpha()]
@property
def minimum_height(self):
return self.description.boundingRect().height() +\
self.title.boundingRect().height() +\
self._title_space +\
self._resize_space
def setup_ui(self):
""" creates the items and applies styles
Returns:
"""
self.setBrush(self._bg_brush)
self.setPen(self._bg_pen)
self.title_bar = Qt.QtWidgets.QGraphicsRectItem(self._bounds[0],
self._bounds[1],
self._bounds[2],
20, # initial start value, will be overwritten later
parent=self)
self.title_bar.setBrush(self._bg_brush)
self.title_bar.setPen(self._bg_pen)
self.title = Qt.QtWidgets.QGraphicsTextItem(self.name, parent=self.title_bar)
self.title.setFont(self._title_font)
self.title.setTextWidth(self._bounds[2])
self.title.setX(self._bounds[0])
self.title.setY(self._bounds[1] - 5)
self.title_bar.setRect(self._bounds[0],
self._bounds[1],
self._bounds[2],
self.title.boundingRect().height())
self.description = Qt.QtWidgets.QGraphicsTextItem(parent=self)
self.description.setFont(self._description_font)
self.description.setTextWidth(self._bounds[2])
self.description.setX(self._bounds[0])
self.description.setY(self._bounds[1] + self.title.boundingRect().height() + self._title_space)
self.handle = Qt.QtWidgets.QGraphicsRectItem(self._bounds[0] + self._bounds[2] - self._handle_size,
self._bounds[1] + self._bounds[3] - self._handle_size,
self._handle_size,
self._handle_size,
parent=self)
self.handle.setBrush(self._handle_brush)
self.handle.setPen(self._bg_pen)
def _adjust_description(self, text):
""" adjusts the description text
Handles the backdrop resizing if required
Args:
text: description text string
Returns:
"""
self.description.setPlainText(text)
# resize backdrop if required
if self.minimum_height >= self._bounds[3]:
self.adjust_to_minimum_height()
def get_contained_items(self):
""" get all node taht
Returns:
"""
return self.scene().items(self.mapToScene(self.boundingRect()), mode=Qt.QtCore.Qt.IntersectsItemShape)
def select_contained_items(self):
""" we have to patch this later in the nodegraph class
Returns:
"""
items = self.get_contained_items()
for item in items:
item.setSelected(True)
def _revert_selection(self):
""" restores previous stored selection
Returns:
"""
for item in self.scene().items():
item.setSelected(False)
if self._selection:
for node in self._selection:
node.setSelected(True)
self._selection = None
def _store_selection(self):
self._selection = [item for item in self.scene().items() if item.isSelected()]
def _remove(self):
""" _remove() gets called via Nodz, so we have to implement it here
Returns:
"""
scene = self.scene()
scene.removeItem(self)
scene.update()
def get_items_in_bounds(self):
raise NotImplementedError
def _underlying_handle(self, point):
""" checks if there is a handle under point
Args:
point: QPointF
Returns: QGraphicRectItem instance
"""
if self.handle.contains(point):
return self.handle
def _perform_resize(self, width_height):
""" backdrop resize
Args:
width_height: QPointF
Returns:
"""
# and text sizes too
self.title.setTextWidth(self._bounds[2])
self.description.setTextWidth(self._bounds[2])
if (width_height.x() > self._minimum_width) and \
(width_height.y() - self._bounds[1] > self.description.boundingRect().height() + self.title.boundingRect().height() + self._resize_space):
# x and y are always 0
# we only have to consider width and height
self._bounds[2] = width_height.x() - self._bounds[0]
self._bounds[3] = width_height.y() - self._bounds[1]
self.set_size(self._bounds[2], self._bounds[3])
def set_size(self, width, height):
""" adjusts width and height of item and all child nodes
Args:
width:
height:
Returns:
"""
self.setRect(self._bounds[0], self._bounds[1], width, height)
self.title_bar.setRect(self._bounds[0],
self._bounds[1],
width,
self.title.boundingRect().height())
self.handle.setRect(self._bounds[0] + width - self._handle_size,
self._bounds[1] + height - self._handle_size,
self._handle_size,
self._handle_size)
self._bounds[2] = width
self._bounds[3] = height
self.description.setY(self._bounds[1] + self.title.boundingRect().height() + self._title_space)
def adjust_to_minimum_height(self):
""" calculates minimum height and adjust height of the item
This has to be called if the description text, title and their sizes will be changed
Returns:
"""
self.set_size(self._bounds[2], self.minimum_height)
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.QtCore.Qt.LeftButton:
self.setSelected(True)
def mousePressEvent(self, event):
""" initializes the backdrop resize procedure
Args:
event:
Returns:
"""
if event.button() == Qt.QtCore.Qt.LeftButton:
selected_handle = self._underlying_handle(event.pos())
if selected_handle:
self._handle_in_use = True
else:
self._store_selection()
self.select_contained_items()
super(Backdrop, self).mousePressEvent(event)