-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprofile_tenure_view.py
1855 lines (1532 loc) · 57 KB
/
profile_tenure_view.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
"""
/***************************************************************************
Name : ProfileTenureView
Description : A widget for rendering a profile's social tenure
relationship.
Date : 9/October/2016
copyright : John Kahiu
email : gkahiu at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
import sys
import math
from PyQt4.QtGui import (
QApplication,
QBrush,
QColor,
QComboBox,
QFont,
QFontMetrics,
QGraphicsItem,
QGraphicsLineItem,
QGraphicsScene,
QGraphicsTextItem,
QGraphicsView,
QGridLayout,
QIcon,
QImage,
QLabel,
QLinearGradient,
QKeyEvent,
QPainter,
QPainterPath,
QPen,
QPixmap,
QPolygonF,
QSizePolicy,
QSpacerItem,
QTextLayout,
QToolButton,
QWidget
)
from PyQt4.QtCore import (
pyqtSignal,
QFile,
QIODevice,
QLineF,
QPointF,
QRect,
QRectF,
QSize,
QSizeF,
Qt
)
import temp_rc
class Arrow(QGraphicsLineItem):
"""
Renders an arrow object (with line and arrow head) from one item to
another. The arrow head size can be customized by specifying the angle
and width of the arrow base.
"""
def __init__(self, start_item, end_item, base_width=None,
tip_angle=None, fill_arrow_head=True,
parent_item=None, scene=None):
"""
Class constructor
:param start_point: Arrow start item.
:type start_point: BaseTenureItem
:param end_point: Arrow end item.
:type end_point: BaseTenureItem
:param base_width: Width (in pixels) of the arrow base. If not
specified, it defaults to 9.0.
:type base_width: float
:param tip_angle: Angle (in radians) between the two line components
at the tip of the arrow. If not specified, it defaults to
math.radians(50.0).
Minimum math.radians(10.0)
Maximum math.radians(<90.0)
:type tip_angle: float
:param fill_arrow_head: True to close and fill the arrow head with
the specified pen and brush settings. Defaults to False.
:type fill_arrow_head: bool
:param parent_item: Parent item.
:type parent_item: QGraphicsItem
:param scene: Scene object.
:type scene: QGraphicsScene
"""
super(Arrow, self).__init__(parent_item, scene)
self._start_item = start_item
self._end_item = end_item
self.base_width = base_width
if self.base_width is None:
self.base_width = 9.0
self._angle = tip_angle
if tip_angle is None:
self._angle = math.radians(50.0)
self.fill_arrow_head = fill_arrow_head
self.setPen(
QPen(
Qt.black,
1,
Qt.SolidLine,
Qt.RoundCap,
Qt.MiterJoin
)
)
self.brush = QBrush(Qt.black)
self._arrow_head_points = []
@property
def start_item(self):
"""
:return: Returns the start item for the arrow.
:rtype: BaseTenureItem
"""
return self._start_item
@property
def end_item(self):
"""
:return: Returns the end item for the arrow.
:rtype: BaseTenureItem
"""
return self._end_item
@property
def start_point(self):
"""
:return: Returns the arrow start point.
:rtype: QPointF
"""
return self._start_item.pos()
@property
def end_point(self):
"""
:return: Returns the arrow end point.
:rtype: QPointF
"""
return self._end_item.pos()
def boundingRect(self):
extra = (self.base_width + self.pen().widthF()) / 2.0
p1 = self.line().p1()
p2 = self.line().p2()
rect = QRectF(
p1, QSizeF(p2.x() - p1.x(), p2.y() - p1.y())
).normalized().adjusted(-extra, -extra, extra, extra)
return rect
def arrow_head_polygon(self):
"""
:return: Returns the arrow head as a QPolygonF object.
:rtype: QPolygonF
"""
return QPolygonF(self._arrow_head_points)
def shape(self):
path = super(Arrow, self).shape()
path.addPolygon(self.arrow_head_polygon())
return path
@property
def angle(self):
"""
:return: Returns the value of the angle at the tip in radians.
:rtype: float
"""
return self._angle
@angle.setter
def angle(self, angle):
"""
Sets the value of the angle to be greater than or equal to
math.radians(10.0) and less than math.radians(90).
:param angle: Angle at the tip of the arrow in radians.
:type angle: float
"""
min_angle = math.radians(10.0)
max_angle = math.radians(90)
if angle < min_angle:
self._angle = min_angle
elif angle > max_angle:
self._angle = max_angle
else:
self._angle = angle
@property
def arrow_points(self):
"""
:return: Returns a collection of points used to draw the arrow head.
:rtype: list(QPointF)
"""
return self._arrow_head_points
def update_position(self):
"""
Updates the position of the line and arrowhead when the positions of
the start and end items change.
"""
line = QLineF(
self.mapFromScene(self.start_item.center()),
self.mapFromScene(self.end_item.center())
)
self.setLine(line)
def _intersection_point(self, item, reference_line):
#Computes the intersection point between the item's line segments
# with the reference line.
intersect_point = QPointF()
for l in item.line_segments():
intersect_type = l.intersect(reference_line, intersect_point)
if intersect_type == QLineF.BoundedIntersection:
return intersect_point
return None
def paint(self, painter, option, widget):
"""
Draw the arrow item.
"""
if self._start_item.collidesWithItem(self._end_item):
return
painter.setPen(self.pen())
center_line = QLineF(self.start_item.center(), self.end_item.center())
#Get intersection points
start_intersection_point = self._intersection_point(self._start_item, center_line)
end_intersection_point = self._intersection_point(self._end_item, center_line)
#Do not draw if there are no intersection points
if start_intersection_point is None or end_intersection_point is None:
return
arrow_line = QLineF(start_intersection_point, end_intersection_point)
self.setLine(arrow_line)
arrow_length = arrow_line.length()
#Setup computation parameters
cnt_factor = (self.base_width / 2.0)/(
math.tan(self._angle / 2.0) * arrow_length
)
cnt_point_delta = (self.base_width/2.0)/arrow_length
#Get arrow base along the line
arrow_base_x = end_intersection_point.x() - (arrow_line.dx() * cnt_factor)
arrow_base_y = end_intersection_point.y() - (arrow_line.dy() * cnt_factor)
#Get deltas to arrow points from centre point of arrow base
cnt_point_dx = -(arrow_line.dy() * cnt_point_delta)
cnt_point_dy = arrow_line.dx() * cnt_point_delta
#Compute absolute arrow positions
A1 = QPointF(arrow_base_x - cnt_point_dx, arrow_base_y - cnt_point_dy)
A2 = QPointF(arrow_base_x + cnt_point_dx, arrow_base_y + cnt_point_dy)
#Update arrow points
self._arrow_head_points = [A1, A2, end_intersection_point]
#Draw main arrow line
painter.drawLine(arrow_line)
#Draw arrow head
if not self.fill_arrow_head:
painter.drawLine(A1, end_intersection_point)
painter.drawLine(end_intersection_point, A2)
else:
painter.setPen(Qt.NoPen)
painter.setBrush(self.brush)
painter.drawPolygon(self.arrow_head_polygon())
class BaseIconRender(object):
"""Renders an icon on the tenure item's header section. This icon can be
can be used to visually depict the nature of the context of the tenure
item. See bounding_rect function for positioning of the icon in the
tenure item. This is an abstract class and needs to be sub-classed for
custom renderers."""
def __init__(self):
#Icon area is 16px by 16px
self.upper_left = QPointF(142.5, 16.5)
self.bottom_right = QPointF(158.5, 32.5)
def bounding_rect(self):
"""
:return: Returns the bounds of the icon and does not factor in the
pen width.
:rtype: QRectF
"""
return QRectF(self.upper_left, self.bottom_right)
@property
def width(self):
"""
:return: Returns the width of the icon plane area.
:rtype: float
"""
return self.bottom_right.x() - self.upper_left.x()
@property
def height(self):
"""
:return: Returns the height of the icon plane area.
:rtype: float
"""
return self.bottom_right.y() - self.upper_left.y()
@property
def pen(self):
"""
:return: Returns a default pen for use in the renderer's painter.
:rtype: QPen
"""
return QPen(Qt.black, 1.0, Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin)
def draw(self, painter, item):
"""
Custom code for rendering the icon. To be implemented by subclasses.
:param painter: Painter object
:type painter: QPainter
:param item: Tenure item object.
:type item: BaseTenureItem
"""
raise NotImplementedError
class EntityIconRenderer(BaseIconRender):
"""Renderer for an icon depicting a data table."""
def draw(self, p, item):
#Save painter state
p.save()
p.setPen(self.pen)
#Draw outline
#Define gradient
grad = QLinearGradient(self.upper_left, self.bottom_right)
grad.setColorAt(0.0, Qt.white)
grad.setColorAt(0.65, QColor('#D2F6FC'))
grad.setColorAt(1.0, QColor('#50E3FC'))
grad_bush = QBrush(grad)
p.setBrush(grad_bush)
p.drawRect(self.bounding_rect())
#Draw column header
cols_header_rect = QRectF(
self.upper_left.x() + 0.5,
self.upper_left.y() + 0.5,
self.width - 1.0,
3.5
)
p.setBrush(QColor('#1399FC'))
p.setPen(Qt.NoPen)
p.drawRect(cols_header_rect)
#Draw vertical column separator
v_start_point = self.upper_left + QPointF(8.0, 0)
v_end_point = self.upper_left + QPointF(8.0, 16.0)
col_vertical_sep = QLineF(v_start_point, v_end_point)
p.setPen(self.pen)
p.drawLine(col_vertical_sep)
#Draw horizontal separators
h1_start_point = self.upper_left + QPointF(0, 4.0)
h1_end_point = self.upper_left + QPointF(self.width, 4.0)
h1_sep = QLineF(h1_start_point, h1_end_point)
p.drawLine(h1_sep)
h_col_pen = QPen(self.pen)
#h_col_pen.setColor(QColor('#32A7BB'))
h_col_pen.setColor(QColor('#1399FC'))
p.setPen(h_col_pen)
delta_v = 12 / 3.0
y = 4.0 + delta_v
for i in range(2):
h_start_point = self.upper_left + QPointF(1.0, y)
h_end_point = self.upper_left + QPointF(self.width - 1.0, y)
h_sep = QLineF(h_start_point, h_end_point)
y += delta_v
p.drawLine(h_sep)
p.restore()
class DocumentIconRenderer(BaseIconRender):
"""Renderer for document icon."""
def draw(self, p, item):
p.save()
#Draw primary folder
outline = QPen(self.pen)
outline.setColor(QColor('#1399FC'))
p.setPen(outline)
back_leaf_brush = QBrush(QColor('#C2E4F8'))
p.setBrush(back_leaf_brush)
leaf_1 = QPainterPath()
leaf_1.moveTo(self.upper_left + QPointF(0, (self.height - 1.5)))
leaf_1.lineTo(self.upper_left + QPointF(0, 5.0))
leaf_1.lineTo(self.upper_left + QPointF(2.0, 5.0))
leaf_1.lineTo(self.upper_left + QPointF(4.0, 2.5))
leaf_1.lineTo(self.upper_left + QPointF(8.0, 2.5))
leaf_1.lineTo(self.upper_left + QPointF(10.0, 5.0))
leaf_1.lineTo(self.upper_left + QPointF(13.0, 5.0))
leaf_1.lineTo(self.upper_left + QPointF(13.0, self.height - 1.5))
leaf_1.closeSubpath()
p.drawPath(leaf_1)
#Front folder leaf
p.setBrush(QBrush(Qt.white))
leaf_2 = QPainterPath()
leaf_2.moveTo(self.upper_left + QPointF(0.5, (self.height - 0.5)))
leaf_2.lineTo(self.upper_left + QPointF(3.0, 8.5))
leaf_2.lineTo(self.upper_left + QPointF(15.5, 8.5))
leaf_2.lineTo(self.upper_left + QPointF(13.0, self.height - 0.5))
leaf_2.closeSubpath()
p.drawPath(leaf_2)
p.restore()
class TenureLinkRenderer(BaseIconRender):
"""Renders an icon depicting a link between the party and
spatial unit."""
def draw(self, p, item):
p.save()
outline = QPen(self.pen)
outline.setColor(QColor('#1399FC'))
outline.setCapStyle(Qt.RoundCap)
outline.setWidthF(1.6)
p.setPen(outline)
#Set segment fill brush
seg_brush = QBrush(QColor('#ECF8FF'))
p.setBrush(seg_brush)
#Draw link segment
link_path = QPainterPath()
link_path.moveTo(self.upper_left + QPointF(2.0, 5.0))
rect_pos = self.upper_left + QPointF(0.5, 5.0)
arc_rect = QRectF(rect_pos, QSizeF(3.0, 6.0))
link_path.arcTo(arc_rect, 90, 180.0)
link_path.lineTo(self.upper_left + QPointF(5.5, 11.0))
rect_pos_2 = self.upper_left + QPointF(4.0, 5.0)
arc_rect_2 = QRectF(rect_pos_2, QSizeF(3.0, 6.0))
link_path.arcTo(arc_rect_2, -90, 180)
link_path.closeSubpath()
p.drawPath(link_path)
#Draw 2nd segment
p.translate(8.5, 0)
p.drawPath(link_path)
#Draw segment connector
p.translate(-8.5, 0)
start_p = self.upper_left + QPointF(5.0, 8.0)
end_p = self.upper_left + QPointF(11.0, 8.0)
p.drawLine(QLineF(start_p, end_p))
p.restore()
class BaseTenureItem(QGraphicsItem):
"""Abstract class that provides core functionality for rendering entity and
social tenure relationship objects corresponding to the entities in a
given profile."""
Type = QGraphicsItem.UserType + 1
def __init__(self, parent=None, scene=None, **kwargs):
super(BaseTenureItem, self).__init__(parent, scene)
self.setFlag(QGraphicsItem.ItemIsMovable)
#Renderer for header icon
self.icon_renderer = kwargs.get('icon_renderer', None)
self.arrows = []
self.pen = QPen(
Qt.black,
0.9,
Qt.SolidLine,
Qt.RoundCap,
Qt.RoundJoin
)
#Display properties
self._default_header = QApplication.translate(
'ProfileTenureView',
'Not Defined'
)
self.header = self._default_header
self.items_title = ''
self.icon_painter = kwargs.pop('icon_painter', None)
self.items = []
self.font_name = 'Consolas'
self._entity = None
#Distance between the primary shape and its shadow
self.shadow_thickness = 4
self._side = 156
self._height = self._side
self._start_pos = 10
#The start and stop positions match the size of the item
stop_position = self._start_pos + self._side
#Main item gradient
self._gradient = QLinearGradient(
self._start_pos,
self._start_pos,
stop_position,
stop_position
)
self._gradient_light = QColor('#fcf2e3')
self._gradient_dark = QColor('#e9dac2')
self._gradient.setColorAt(0.0, self._gradient_light)
self._gradient.setColorAt(1.0, self._gradient_dark)
self._brush = QBrush(self._gradient)
#Shadow gradient
#The start and stop positions match the size of the item
shadow_start_pos = self._start_pos + self.shadow_thickness
shadow_stop_pos = self._start_pos + self._side + self.shadow_thickness
self._shadow_gradient = QLinearGradient(
shadow_start_pos,
shadow_start_pos,
shadow_stop_pos,
shadow_stop_pos
)
self._shadow_gradient.setColorAt(0.0, QColor('#f7f8f9'))
self._shadow_gradient.setColorAt(1.0, QColor('#d1d1d1'))
self._brush = QBrush(self._gradient)
self._text_highlight_color = QColor('#E74C3C')
self._text_item_color = QColor('#CC0000')
self._normal_text_color = Qt.black
def type(self):
return BaseTenureItem.Type
def remove_arrow(self, arrow):
"""
Removes an arrow from the collection.
:param arrow: Arrow item.
:type arrow: Arrow
"""
try:
self.arrows.remove(arrow)
except ValueError:
pass
def remove_arrows(self):
"""
Removes all arrows associated with this item and related item.
"""
for ar in self.arrows[:]:
ar.start_item.remove_arrow(ar)
ar.end_item.remove_arrow(ar)
self.scene().removeItem(ar)
def add_arrow(self, arrow):
"""
Adds arrow item to the collection.
:param arrow: Arrow item.
:type arrow: Arrow
"""
self.arrows.append(arrow)
def boundingRect(self):
extra = self.pen.widthF() / 2.0
return QRectF(
self._start_pos - extra,
self._start_pos - extra,
self.width + self.shadow_thickness + extra,
self.height + self.shadow_thickness + extra
)
def invalidate(self):
"""
Reset the title and items.
"""
self.header = self._default_header
self.items = []
self.update()
@property
def brush(self):
"""
:return: Returns the brush used for rendering the entity item.
:rtype: QBrush
"""
return self._brush
@property
def header_font(self):
"""
:return: Returns the font object used to render the header text.
:rtype: QFont
"""
return QFont(self.font_name, 13, 63)
@property
def items_title_font(self):
"""
:return: Returns the font object used to render the items header text.
:rtype: QFont
"""
return QFont(self.font_name, 10)
@property
def items_font(self):
"""
:return: Returns the font object used to render multiline items.
:rtype: QFont
"""
return QFont(self.font_name, 9)
@property
def entity(self):
"""
:return: Returns the entity associated with the rendered.
:rtype: Entity
"""
return self._entity
def auto_adjust_height(self):
"""
:return: True if the height should be automatically adjusted to fit
the number of items specified. Otherwise, False; in this case, the
height is equal to the default height of the item. Items that exceed
the height of the items area will not be shown.
To be overridden by sub-classes.
:rtype: bool
"""
return True
@entity.setter
def entity(self, entity):
"""
Sets the current entity object.
:param entity: Entity object.
:type entity: Entity
"""
self._entity = entity
self.prepareGeometryChange()
self._on_set_entity()
def _on_set_entity(self):
"""
Update attributes based on the entity's attributes. To be implemented
by subclasses.
"""
raise NotImplementedError
@property
def width(self):
"""
:return: Returns the logical width of the item.
:rtype: float
"""
return float(self._side + self.shadow_thickness)
@property
def height(self):
"""
:return: Returns the logical height of the item. If
auto_adjust_height is True then the height will be automatically
adjusted to match number of items, else it will be equal to the width
of the item.
"""
return float(self._height + self.shadow_thickness)
def scene_bounding_rect(self):
"""
:return: Returns the bounding rect of the primary item in scene
coordinates, this does not include the shadow thickness.
:rtype: QRectF
"""
local_start_point = QPointF(self._start_pos, self._start_pos)
scene_start_point = self.mapToScene(local_start_point)
return QRectF(scene_start_point, QSizeF(self._side, self._height))
def center(self):
"""
:return: Returns the center point of the item in scene coordinates.
:rtype: QPointF
"""
return self.scene_bounding_rect().center()
def line_segments(self):
"""
:return: Returns a list of QLineF objects that constitute the scene
bounding rect. The line segments are in scene coordinates.
:rtype: QRectF
"""
lines = []
rect = self.scene_bounding_rect()
poly = QPolygonF(rect)
for i, p in enumerate(poly):
if i == len(poly) - 1:
break
p1 = poly[i]
#Close to first point if the last item is reached
if i + 1 == len(poly):
p2 = poly[0]
else:
p2 = poly[i + 1]
#Construct line object
line = QLineF(p1, p2)
lines.append(line)
return lines
def _elided_text(self, font, text, width):
#Returns elided version of the text if greater than the width
fm = QFontMetrics(font)
return unicode(fm.elidedText(text, Qt.ElideRight, width))
def _elided_items(self, font, width):
#Formats each item text to incorporate an elide if need be and
# return the items in a list.
return map(
lambda item: self._elided_text(font, item, width),
self.items
)
def items_size(self, items):
"""
Computes an appropriate width and height of an items' text separated
by a new line.
:param items: Iterable containing string items for which the size
will be computed.
:type items: list
:return: Returns a size object that fits the items' text in the list.
:rtype: QSize
"""
fm = QFontMetrics(self.items_font)
return fm.size(Qt.TextWordWrap, '\n'.join(items))
def items_by_height(self, height, items):
"""
:param height: Height in pixels in which the subset of items will fit.
:type height: int
:return: Returns a subset of items which fit the specified height.
:rtype: list
"""
items_sub = []
fm = QFontMetrics(self.items_font)
for i in items:
sz = self.items_size(items_sub)
if sz.height() > height:
break
items_sub.append(i)
return items_sub
def _font_height(self, font, text):
"""
Computes the height for the given font object.
:param font: Font object.
:type font: QFont
:param text: Text
:type text: str
:return: Returns the minimum height for the given font object.
:rtype: int
"""
fm = QFontMetrics(font)
return fm.size(Qt.TextSingleLine, text).height()
def draw_text(self, painter, text, font, bounds, alignment=Qt.AlignCenter):
"""
Provides a device independent mechanism for rendering fonts
regardless of the device's resolution. By default, the text will be
centred. This is a workaround for the font scaling issue for devices
with different resolutions.
:param painter: Painter object.
:type painter: QPainter
:param text: Text to be rendered.
:type text: str
:param font: Font for rendering the text.
:type font: QFont
:param bounds: Rect object which will provide the reference point for
drawing the text.
:type bounds: QRectF
:param alignment: Qt enums used to describe alignment. AlignCenter is
the default. Accepts bitwise OR for horizontal and vertical flags.
:type alignment: int
"""
layout = QTextLayout(text, font)
layout.beginLayout()
#Create the required number of lines in the layout
while layout.createLine().isValid():
pass
layout.endLayout()
y = 0
max_width = 0
#Set line positions relative to the layout
for i in range(layout.lineCount()):
line = layout.lineAt(i)
max_width = max(max_width, line.naturalTextWidth())
line.setPosition(QPointF(0, y))
y += line.height()
#Defaults
start_x = bounds.left()
start_y = bounds.top()
#Horizontal flags
if (alignment & Qt.AlignLeft) == Qt.AlignLeft:
start_x = bounds.left()
elif (alignment & Qt.AlignCenter) == Qt.AlignCenter or \
(alignment & Qt.AlignHCenter) == Qt.AlignHCenter:
start_x = bounds.left() + (bounds.width() - max_width) / 2.0
#Vertical flags
if (alignment == Qt.AlignTop) == Qt.AlignTop:
start_y = bounds.top()
elif (alignment & Qt.AlignCenter) == Qt.AlignCenter or \
(alignment & Qt.AlignVCenter) == Qt.AlignVCenter:
start_y = bounds.top() + (bounds.height() - y) / 2.0
layout.draw(painter, QPointF(start_x, start_y))
def paint(self, painter, option, widget=None):
"""
Performs the painting of the tenure item based on the object's
attributes.
:param painter: Performs painting operation on the item.
:type painter: QPainter
:param option: Provides style option for the item.
:type option: QStyleOptionGraphicsItem
:param widget: Provides points to the widget that is being painted on.
:type widget: QWidget
"""
shadow_start_pos = self._start_pos + self.shadow_thickness
#Use height of subsections to compute the appropriate height
header_height = self._font_height(self.header_font, self.header) + 7
items_title_height = self._font_height(
self.items_title_font,
self.items_title
)
margin = 1
fixed_height = header_height + items_title_height + (6 * margin)
if self.auto_adjust_height():
items_height = self.items_size(self.items).height() + 2
main_item_height = max(self._side, fixed_height + items_height)
else:
items_height = self._side - fixed_height
main_item_height = self._side
self._height = main_item_height
shadow_rect = QRect(
shadow_start_pos,
shadow_start_pos,
self._side,
main_item_height
)
main_item_rect = QRect(
self._start_pos,
self._start_pos,
self._side,
main_item_height
)
painter_pen = painter.pen()
painter_pen.setColor(self._normal_text_color)
painter_pen.setWidth(0)
#Create shadow effect using linear gradient
painter.setBrush(self._shadow_gradient)
painter.setPen(Qt.NoPen)
painter.drawRect(shadow_rect)
painter.setPen(self.pen)
painter.setBrush(self._brush)
#Main item outline
painter.drawRect(main_item_rect)
line_y_pos = header_height + margin * 2
painter.drawLine(
self._start_pos,
self._start_pos + line_y_pos,
self._start_pos + self._side,
self._start_pos + line_y_pos
)
#Draw header text
header_start_pos = self._start_pos + margin
header_rect = QRect(
header_start_pos,
header_start_pos,
self._side - (margin * 2),
header_height
)
#Adjust header text area if there is an icon renderer
if not self.icon_renderer is None:
init_width = header_rect.width()
adj_width = init_width - (self.icon_renderer.width + 6)
header_rect.setWidth(adj_width)
#Draw header icon if renderer is available
if not self.icon_renderer is None:
if isinstance(self.icon_renderer, BaseIconRender):
self.icon_renderer.draw(painter, self)
painter.setFont(self.header_font)
if self.header == self._default_header:
painter.setPen(self._text_highlight_color)
else:
painter.setPen(self._normal_text_color)
elided_header = self._elided_text(
self.header_font,
self.header,
header_rect.width()
)
#print elided_header
self.draw_text(painter, elided_header, self.header_font, header_rect)
#Draw items header
items_title_rect = QRect(
header_start_pos + 1,
header_height + items_title_height - 1,
self._side - (margin * 4),
items_title_height
)
painter.setFont(self.items_title_font)
painter.setPen(QColor('#c3b49c'))
items_title_brush = QBrush(self._gradient_dark)
painter.setBrush(items_title_brush)
painter.drawRect(items_title_rect)
#Adjust left margin of items title
items_title_rect.adjust(1, 0, 0, 0)
painter.setPen(self._normal_text_color)