File: qt_graphics_view.py

package info (click to toggle)
python-enamlx 0.6.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 388 kB
  • sloc: python: 3,338; makefile: 18
file content (1188 lines) | stat: -rw-r--r-- 38,294 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on Sept 4, 2018
"""
import warnings

from atom.api import Atom, Coerced, Int, Typed, atomref
from enaml.drag_drop import DropAction
from enaml.qt.q_resource_helpers import (
    get_cached_qcolor,
    get_cached_qfont,
    get_cached_qimage,
)
from enaml.qt.qt_control import QtControl
from enaml.qt.qt_drag_drop import QtDropEvent
from enaml.qt.qt_toolkit_object import QtToolkitObject
from enaml.qt.qt_widget import QtWidget, focus_registry
from enaml.qt.QtCore import QPoint, QPointF, QRectF, Qt
from enaml.qt.QtGui import (
    QBrush,
    QColor,
    QCursor,
    QDrag,
    QPainter,
    QPen,
    QPixmap,
    QPolygonF,
)
from enaml.qt.QtWidgets import (
    QFrame,
    QGraphicsEllipseItem,
    QGraphicsItem,
    QGraphicsItemGroup,
    QGraphicsLineItem,
    QGraphicsObject,
    QGraphicsPathItem,
    QGraphicsPixmapItem,
    QGraphicsPolygonItem,
    QGraphicsProxyWidget,
    QGraphicsRectItem,
    QGraphicsScene,
    QGraphicsSimpleTextItem,
    QGraphicsView,
    QWidgetAction,
)
from enaml.widgets.widget import Feature

from enamlx.widgets.graphics_view import (
    GraphicFeature,
    Point,
    ProxyAbstractGraphicsShapeItem,
    ProxyGraphicsEllipseItem,
    ProxyGraphicsImageItem,
    ProxyGraphicsItem,
    ProxyGraphicsItemGroup,
    ProxyGraphicsLineItem,
    ProxyGraphicsPathItem,
    ProxyGraphicsPolygonItem,
    ProxyGraphicsRectItem,
    ProxyGraphicsTextItem,
    ProxyGraphicsView,
    ProxyGraphicsWidget,
)

PEN_STYLES = {
    "none": Qt.NoPen,
    "solid": Qt.SolidLine,
    "dash": Qt.DashLine,
    "dot": Qt.DotLine,
    "dash_dot": Qt.DashDotLine,
    "dash_dot_dot": Qt.DashDotDotLine,
    "custom": Qt.CustomDashLine,
}

CAP_STYLES = {
    "square": Qt.SquareCap,
    "flat": Qt.FlatCap,
    "round": Qt.RoundCap,
}

JOIN_STYLES = {
    "bevel": Qt.BevelJoin,
    "miter": Qt.MiterJoin,
    "round": Qt.RoundJoin,
}

BRUSH_STYLES = {
    "solid": Qt.SolidPattern,
    "dense1": Qt.Dense1Pattern,
    "dense2": Qt.Dense2Pattern,
    "dense3": Qt.Dense3Pattern,
    "dense4": Qt.Dense4Pattern,
    "dense5": Qt.Dense5Pattern,
    "dense6": Qt.Dense6Pattern,
    "dense7": Qt.Dense7Pattern,
    "horizontal": Qt.HorPattern,
    "vertical": Qt.VerPattern,
    "cross": Qt.CrossPattern,
    "bdiag": Qt.BDiagPattern,
    "fdiag": Qt.FDiagPattern,
    "diag": Qt.DiagCrossPattern,
    "linear": Qt.LinearGradientPattern,
    "radial": Qt.RadialGradientPattern,
    "conical": Qt.ConicalGradientPattern,
    "texture": Qt.TexturePattern,
    "none": Qt.NoBrush,
}


DRAG_MODES = {
    "none": QGraphicsView.NoDrag,
    "scroll": QGraphicsView.ScrollHandDrag,
    "selection": QGraphicsView.RubberBandDrag,
}

# --------------------------------------------------------------------------
# Qt Resource Helpers
# --------------------------------------------------------------------------


def QPen_from_Pen(pen):
    qpen = QPen()
    if pen.color:
        qpen.setColor(get_cached_qcolor(pen.color))
    qpen.setWidth(int(pen.width))
    qpen.setStyle(PEN_STYLES.get(pen.line_style))
    qpen.setCapStyle(CAP_STYLES.get(pen.cap_style))
    qpen.setJoinStyle(JOIN_STYLES.get(pen.join_style))
    if pen.line_style == "custom":
        qpen.setDashPattern(*pen.dash_pattern)
    return qpen


def QBrush_from_Brush(brush):
    qbrush = QBrush()
    if brush.color:
        qbrush.setColor(get_cached_qcolor(brush.color))
    if brush.image:
        qbrush.setTextureImage(get_cached_qimage(brush.image))
        qbrush.setStyle(Qt.TexturePattern)
    else:
        qbrush.setStyle(BRUSH_STYLES.get(brush.style))
    return qbrush


def get_cached_qpen(pen):
    qpen = pen._tkdata
    if not isinstance(qpen, QPen):
        qpen = pen._tkdata = QPen_from_Pen(pen)
    return qpen


def get_cached_qbrush(brush):
    qbrush = brush._tkdata
    if not isinstance(qbrush, QBrush):
        qbrush = brush._tkdata = QBrush_from_Brush(brush)
    return qbrush


# --------------------------------------------------------------------------
# Mixin classes
# --------------------------------------------------------------------------
class FeatureMixin(Atom):
    """A mixin that provides focus and mouse features."""

    #: A private copy of the declaration features. This ensures that
    #: feature cleanup will proceed correctly in the event that user
    #: code modifies the declaration features value at runtime.
    _features = Coerced(Feature, (0,))
    _extra_features = Coerced(GraphicFeature, (0,))

    #: Internal storage for the shared widget action.
    _widget_action = Typed(QWidgetAction)

    #: Internal storage for the drag origin position.
    _drag_origin = Typed(QPointF)

    # --------------------------------------------------------------------------
    # Private API
    # --------------------------------------------------------------------------
    def _setup_features(self):
        """Setup the advanced widget feature handlers."""
        features = self._features = self.declaration.features
        if not features:
            return
        if features & Feature.FocusTraversal:
            self.hook_focus_traversal()
        if features & Feature.FocusEvents:
            self.hook_focus_events()
        if features & Feature.DragEnabled:
            self.hook_drag()
        if features & Feature.DropEnabled:
            self.hook_drop()

        features = self._extra_features
        if features & GraphicFeature.WheelEvent:
            self.hook_wheel()
        if features & GraphicFeature.DrawEvent:
            self.hook_draw()

    def _teardown_features(self):
        """Teardowns the advanced widget feature handlers."""
        features = self._features
        if not features:
            return
        if features & Feature.FocusTraversal:
            self.unhook_focus_traversal()
        if features & Feature.FocusEvents:
            self.unhook_focus_events()
        if features & Feature.DragEnabled:
            self.unhook_drag()
        if features & Feature.DropEnabled:
            self.unhook_drop()

        features = self._extra_features
        if features & GraphicFeature.WheelEvent:
            self.unhook_wheel()
        if features & GraphicFeature.DrawEvent:
            self.unhook_draw()

    # --------------------------------------------------------------------------
    # Protected API
    # --------------------------------------------------------------------------
    def tab_focus_request(self, reason):
        """Handle a custom tab focus request.

        This method is called when focus is being set on the proxy
        as a result of a user-implemented focus traversal handler.
        This can be reimplemented by subclasses as needed.

        Parameters
        ----------
        reason : Qt.FocusReason
            The reason value for the focus request.

        Returns
        -------
        result : bool
            True if focus was set, False otherwise.

        """
        widget = self.focus_target()
        if not widget.focusPolicy & Qt.TabFocus:
            return False
        if not widget.isEnabled():
            return False
        if not widget.isVisibleTo(widget.window()):
            return False
        widget.setFocus(reason)
        return False

    def focus_target(self):
        """Return the current focus target for a focus request.

        This can be reimplemented by subclasses as needed. The default
        implementation of this method returns the current proxy widget.

        """
        return self.widget

    def hook_focus_traversal(self):
        """Install the hooks for focus traversal.

        This method may be overridden by subclasses as needed.

        """
        self.widget.focusNextPrevChild = self.focusNextPrevChild

    def unhook_focus_traversal(self):
        """Remove the hooks for the next/prev child focusing.

        This method may be overridden by subclasses as needed.

        """
        del self.widget.focusNextPrevChild

    def hook_focus_events(self):
        """Install the hooks for focus events.

        This method may be overridden by subclasses as needed.

        """
        widget = self.widget
        widget.focusInEvent = self.focusInEvent
        widget.focusOutEvent = self.focusOutEvent

    def unhook_focus_events(self):
        """Remove the hooks for the focus events.

        This method may be overridden by subclasses as needed.

        """
        widget = self.widget
        del widget.focusInEvent
        del widget.focusOutEvent

    def focusNextPrevChild(self, next_child):
        """The default 'focusNextPrevChild' implementation."""
        fd = focus_registry.focused_declaration()
        if next_child:
            child = self.declaration.next_focus_child(fd)
            reason = Qt.TabFocusReason
        else:
            child = self.declaration.previous_focus_child(fd)
            reason = Qt.BacktabFocusReason
        if child is not None and child.proxy_is_active:
            return child.proxy.tab_focus_request(reason)
        widget = self.widget
        return type(widget).focusNextPrevChild(widget, next_child)

    def focusInEvent(self, event):
        """The default 'focusInEvent' implementation."""
        widget = self.widget
        type(widget).focusInEvent(widget, event)
        self.declaration.focus_gained()

    def focusOutEvent(self, event):
        """The default 'focusOutEvent' implementation."""
        widget = self.widget
        type(widget).focusOutEvent(widget, event)
        self.declaration.focus_lost()

    def hook_drag(self):
        """Install the hooks for drag operations."""
        widget = self.widget
        widget.mousePressEvent = self.mousePressEvent
        widget.mouseMoveEvent = self.mouseMoveEvent
        widget.mouseReleaseEvent = self.mouseReleaseEvent

    def unhook_drag(self):
        """Remove the hooks for drag operations."""
        widget = self.widget
        del widget.mousePressEvent
        del widget.mouseMoveEvent
        del widget.mouseReleaseEvent

    def mousePressEvent(self, event):
        """Handle the mouse press event for a drag operation."""
        if event.button() == Qt.LeftButton:
            self._drag_origin = event.pos()
        widget = self.widget
        type(widget).mousePressEvent(widget, event)

    def mouseMoveEvent(self, event):
        """Handle the mouse move event for a drag operation."""
        # if event.buttons() & Qt.LeftButton and self._drag_origin is not None:
        # dist = (event.pos() - self._drag_origin).manhattanLength()
        # if dist >= QApplication.startDragDistance():
        # self.do_drag(event.widget())
        # self._drag_origin = None
        # return # Don't returns
        widget = self.widget
        type(widget).mouseMoveEvent(widget, event)

    def mouseReleaseEvent(self, event):
        """Handle the mouse release event for the drag operation."""
        if event.button() == Qt.LeftButton:
            self._drag_origin = None
        widget = self.widget
        type(widget).mouseReleaseEvent(widget, event)

    def hook_drop(self):
        """Install hooks for drop operations."""
        widget = self.widget
        widget.setAcceptDrops(True)
        widget.dragEnterEvent = self.dragEnterEvent
        widget.dragMoveEvent = self.dragMoveEvent
        widget.dragLeaveEvent = self.dragLeaveEvent
        widget.dropEvent = self.dropEvent

    def unhook_drop(self):
        """Remove hooks for drop operations."""
        widget = self.widget
        widget.setAcceptDrops(False)
        del widget.dragEnterEvent
        del widget.dragMoveEvent
        del widget.dragLeaveEvent
        del widget.dropEvent

    def do_drag(self, widget):
        """Perform the drag operation for the widget.

        Parameters
        ----------
        widget: QWidget
            A reference to the viewport widget.

        """
        drag_data = self.declaration.drag_start()
        if drag_data is None:
            return
        # widget = self.widget
        qdrag = QDrag(widget)
        qdrag.setMimeData(drag_data.mime_data.q_data())
        if drag_data.image is not None:
            qimg = get_cached_qimage(drag_data.image)
            qdrag.setPixmap(QPixmap.fromImage(qimg))
        # else:
        # if __version_info__ < (5, ):
        # qdrag.setPixmap(QPixmap.grabWidget(self.widget))
        # else:
        # qdrag.setPixmap(widget.grab())
        if drag_data.hotspot:
            qdrag.setHotSpot(QPoint(*drag_data.hotspot))
        else:
            cursor_position = widget.mapFromGlobal(QCursor.pos())
            qdrag.setHotSpot(cursor_position)
        default = Qt.DropAction(drag_data.default_drop_action)
        supported = Qt.DropActions(drag_data.supported_actions)
        qresult = qdrag.exec_(supported, default)
        self.declaration.drag_end(drag_data, DropAction(int(qresult)))

    def dragEnterEvent(self, event):
        """Handle the drag enter event for the widget."""
        self.declaration.drag_enter(QtDropEvent(event))

    def dragMoveEvent(self, event):
        """Handle the drag move event for the widget."""
        self.declaration.drag_move(QtDropEvent(event))

    def dragLeaveEvent(self, event):
        """Handle the drag leave event for the widget."""
        self.declaration.drag_leave()

    def dropEvent(self, event):
        """Handle the drop event for the widget."""
        self.declaration.drop(QtDropEvent(event))

    def hook_wheel(self):
        """Install the hooks for wheel events."""
        widget = self.widget
        widget.wheelEvent = self.wheelEvent

    def unhook_wheel(self):
        """Removes the hooks for wheel events."""
        widget = self.widget
        del widget.wheelEvent

    def wheelEvent(self, event):
        """Handle the mouse wheel event for the widget."""
        self.declaration.wheel_event(event)

    def hook_draw(self):
        """Remove the hooks for the draw (paint) event.

        This method may be overridden by subclasses as needed.

        """
        widget = self.widget
        widget.paint = self.draw

    def unhook_draw(self):
        """Remove the hooks for the draw (paint) event.

        This method may be overridden by subclasses as needed.

        """
        widget = self.widget
        del widget.paint

    def draw(self, painter, options, widget):
        """Handle the draw event for the widget."""
        self.declaration.draw(painter, options, widget)

    # --------------------------------------------------------------------------
    # Framework API
    # --------------------------------------------------------------------------
    def get_action(self, create=False):
        """Get the shared widget action for this widget.

        This API is used to support widgets in tool bars and menus.

        Parameters
        ----------
        create : bool, optional
            Whether to create the action if it doesn't already exist.
            The default is False.

        Returns
        -------
        result : QWidgetAction or None
            The cached widget action or None, depending on arguments.

        """
        action = self._widget_action
        if action is None and create:
            action = self._widget_action = QWidgetAction(None)
            action.setDefaultWidget(self.widget)
        return action


# --------------------------------------------------------------------------
# Toolkit implementations
# --------------------------------------------------------------------------
class QtGraphicsView(QtControl, ProxyGraphicsView):
    #: Internal widget
    widget = Typed(QGraphicsView)

    #: Internal scene
    scene = Typed(QGraphicsScene)

    #: View Range
    view_range = Typed(QRectF, (0, 0, 1, 1))

    #: Custom features
    _extra_features = Coerced(GraphicFeature, (0,))

    #: Cyclic notification guard. This a bitfield of multiple guards.
    _guards = Int(0)

    def create_widget(self):
        self.scene = QGraphicsScene()
        self.widget = QGraphicsView(self.scene, self.parent_widget())

    def init_widget(self):
        d = self.declaration
        self._extra_features = d.extra_features
        super(QtGraphicsView, self).init_widget()

        widget = self.widget
        widget.setCacheMode(QGraphicsView.CacheBackground)
        widget.setFocusPolicy(Qt.StrongFocus)
        widget.setFrameShape(QFrame.NoFrame)
        widget.setViewportUpdateMode(QGraphicsView.BoundingRectViewportUpdate)
        widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        widget.setViewportUpdateMode(QGraphicsView.MinimalViewportUpdate)
        widget.setResizeAnchor(QGraphicsView.AnchorViewCenter)
        widget.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        widget.setMouseTracking(True)

        self.set_drag_mode(d.drag_mode)
        self.set_renderer(d.renderer)
        self.set_antialiasing(d.antialiasing)
        self.scene.selectionChanged.connect(self.on_selection_changed)

    def init_layout(self):
        super(QtGraphicsView, self).init_layout()
        scene = self.scene
        for item in self.scene_items():
            scene.addItem(item)

        self.set_view_range(self.view_range)

    def child_added(self, child):
        if isinstance(child, QtGraphicsItem):
            self.scene.addItem(child.widget)
        else:
            super(QtGraphicsView, self).child_added(child)

    def child_removed(self, child):
        if isinstance(child, QtGraphicsItem):
            self.scene.removeItem(child.widget)
        else:
            super(QtGraphicsView, self).child_removed(child)

    def scene_items(self):
        for w in self.children():
            if isinstance(w, QtGraphicsItem):
                yield w.widget

    # --------------------------------------------------------------------------
    # GraphicFeature API
    # --------------------------------------------------------------------------
    def _setup_features(self):
        super(QtGraphicsView, self)._setup_features()
        features = self._extra_features
        if features & GraphicFeature.MouseEvent:
            self.hook_drag()
        if features & GraphicFeature.WheelEvent:
            self.hook_wheel()
        self.hook_resize()

    def _teardown_features(self):
        super(QtGraphicsView, self)._teardown_features()
        features = self._extra_features
        if features & GraphicFeature.MouseEvent:
            self.unhook_drag()
        if features & GraphicFeature.WheelEvent:
            self.unhook_wheel()
        self.unhook_resize()

    def hook_wheel(self):
        """Install the hooks for wheel events."""
        widget = self.widget
        widget.wheelEvent = self.wheelEvent

    def unhook_wheel(self):
        """Removes the hooks for wheel events."""
        widget = self.widget
        del widget.wheelEvent

    def hook_draw(self):
        """Install the hooks for background draw events."""
        widget = self.widget
        widget.drawBackground = self.drawBackground

    def unhook_draw(self):
        """Removes the hooks for background draw events."""
        widget = self.widget
        del widget.drawBackground

    def hook_resize(self):
        """Install the hooks for resize events."""
        widget = self.widget
        widget.resizeEvent = self.resizeEvent

    def unhook_resize(self):
        """Removes the hooks for resize events."""
        widget = self.widget
        del widget.resizeEvent

    # --------------------------------------------------------------------------
    # QGraphicView API
    # --------------------------------------------------------------------------
    def wheelEvent(self, event):
        """Handle the wheel event for the widget."""
        self.declaration.wheel_event(event)

    def drawBackground(self, painter, rect):
        """Handle the drawBackground request"""
        self.declaration.draw_background(painter, rect)

    def mousePressEvent(self, event):
        """Handle the mouse press event for a drag operation."""
        self.declaration.mouse_press_event(event)
        super(QtGraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        """Handle the mouse move event for a drag operation."""
        self.declaration.mouse_move_event(event)
        super(QtGraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        """Handle the mouse release event for the drag operation."""
        self.declaration.mouse_release_event(event)
        super(QtGraphicsView, self).mouseReleaseEvent(event)

    def resizeEvent(self, event):
        """Resize the view range to match the widget size"""
        d = self.declaration
        widget = self.widget

        if d.auto_range:
            size = self.widget.size()
            view_range = QRectF(0, 0, size.width(), size.height())
            # view_range = self.scene.itemsBoundingRect()
        else:
            # Return the boundaries of the view in scene coordinates
            r = QRectF(widget.rect())
            view_range = widget.viewportTransform().inverted()[0].mapRect(r)
        self.set_view_range(view_range)

    # --------------------------------------------------------------------------
    # ProxyGraphicsView API
    # --------------------------------------------------------------------------
    def set_view_range(self, view_range):
        """Set the visible scene rect to override the default behavior
        of limiting panning and viewing to the graphics items view.

        Based on Luke Campagnola's updateMatrix of pyqtgraph's GraphicsView

        """
        d = self.declaration
        self.view_range = view_range
        widget = self.widget
        widget.setSceneRect(view_range)
        if d.auto_range:
            widget.resetTransform()
        else:
            if d.lock_aspect_ratio:
                flags = Qt.KeepAspectRatio
            else:
                flags = Qt.IgnoreAspectRatio
            widget.fitInView(view_range, flags)

    def set_drag_mode(self, mode):
        self.widget.setDragMode(DRAG_MODES.get(mode))

    def set_auto_range(self, enabled):
        self.set_view_range(self.view_range)

    def set_lock_aspect_ratio(self, locked):
        self.set_view_range(self.view_range)

    def set_antialiasing(self, enabled):
        flags = self.widget.renderHints()
        if enabled:
            flags |= QPainter.Antialiasing
        else:
            flags &= ~QPainter.Antialiasing
        self.widget.setRenderHints(flags)

    def set_renderer(self, renderer):
        """Set the viewport widget."""
        viewport = None
        if renderer == "opengl":
            from enaml.qt.QtWidgets import QOpenGLWidget

            viewport = QOpenGLWidget()
        elif renderer == "default":
            try:
                from enaml.qt.QtWidgets import QOpenGLWidget

                viewport = QOpenGLWidget()
            except ImportError as e:
                warnings.warn("QOpenGLWidget could not be imported: {}".format(e))
        self.widget.setViewport(viewport)

    def set_selected_items(self, items):
        if self._guards & 0x01:
            return
        self.scene.clearSelection()
        for item in items:
            item.selected = True

    def on_selection_changed(self):
        """Callback invoked one the selection has changed."""
        d = self.declaration
        selection = self.scene.selectedItems()
        self._guards |= 0x01
        try:
            d.selected_items = [
                item.ref().declaration for item in selection if item.ref()
            ]
        finally:
            self._guards &= ~0x01

    def set_background(self, background):
        """Set the background color of the widget."""
        scene = self.scene
        scene.setBackgroundBrush(QColor.fromRgba(background.argb))

    def get_item_at(self, point):
        item = self.scene.getItemAt(point.x, point.y)
        if item and item.ref():
            return item.ref().declaration

    def get_items_at(self, point):
        items = self.scene.items(point.x, point.y)
        return [item.ref().declaration for item in items if item.ref()]

    def get_items_in(self, top_left, bottom_right):
        qrect = QRectF(
            QPointF(top_left.x, top_left.y), QPointF(bottom_right.x, bottom_right.y)
        )
        items = self.scene.items(qrect)
        return [item.ref().declaration for item in items if item.ref()]

    def fit_in_view(self, item):
        self.widget.fitInView(item.proxy.widget)

    def center_on(self, item):
        if isinstance(item, Point):
            self.widget.centerOn(item.x, item.y)
        else:
            self.widget.centerOn(item.proxy.widget)

    def reset_view(self):
        self.widget.resetTransform()

    def translate_view(self, x, y):
        view_range = self.view_range.adjusted(x, y, x, y)
        self.set_view_range(view_range)
        return view_range

    def scale_view(self, x, y):
        """Scale the zoom but keep in in the min and max zoom bounds."""
        d = self.declaration
        sx, sy = float(x), float(y)
        if d.lock_aspect_ratio:
            sy = sx
        view_range = self.view_range
        center = view_range.center()
        w, h = view_range.width() / sx, view_range.height() / sy
        cx, cy = center.x(), center.y()
        x = cx - (cx - view_range.left()) / sx
        y = cy - (cy - view_range.top()) / sy
        view_range = QRectF(x, y, w, h)
        self.set_view_range(view_range)
        return view_range

    def rotate_view(self, angle):
        self.widget.rotate(angle)

    def map_from_scene(self, point):
        qpoint = self.widget.mapFromScene(point.x, point.y)
        return Point(qpoint.x(), qpoint.y())

    def map_to_scene(self, point):
        qpoint = self.widget.mapToScene(point.x, point.y)
        return Point(qpoint.x(), qpoint.y())

    def pixel_density(self):
        tr = self.widget.transform().inverted()[0]
        p = tr.map(QPoint(1, 1)) - tr.map(QPoint(0, 0))
        return Point(p.x(), p.y())


class QtGraphicsItem(QtToolkitObject, ProxyGraphicsItem, FeatureMixin):
    """QtGraphicsItem is essentially a copy of QtWidget except that
    it uses `self.widget`, `create_widget` and `init_widget` instead of
    widget.

    """

    #: Internal item
    widget = Typed(QGraphicsObject)

    #: Cyclic notification guard. This a bitfield of multiple guards.
    #: 0x01 is position
    _guards = Int(0)

    # --------------------------------------------------------------------------
    # Initialization API
    # --------------------------------------------------------------------------
    def create_widget(self):
        self.widget = QGraphicsObject(self.parent_widget())

    def init_widget(self):
        widget = self.widget

        # Save a reference so we can retrieve the QtGraphicsItem
        # from the QGraphicsItem
        widget.ref = atomref(self)

        focus_registry.register(widget, self)
        d = self.declaration
        self._extra_features = d.extra_features
        self._setup_features()

        if d.selectable:
            self.set_selectable(d.selectable)
        if d.movable:
            self.set_movable(d.movable)
        if d.tool_tip:
            self.set_tool_tip(d.tool_tip)
        if d.status_tip:
            self.set_status_tip(d.status_tip)
        if not d.enabled:
            self.set_enabled(d.enabled)
        if not d.visible:
            self.set_visible(d.visible)
        if d.opacity != 1:
            self.set_opacity(d.opacity)
        if d.rotation:
            self.set_rotation(d.rotation)
        if d.scale != 1:
            self.set_scale(d.scale)
        self.set_position(d.position)
        self.hook_item_change()

    def init_layout(self):
        pass

    # --------------------------------------------------------------------------
    # ProxyToolkitObject API
    # --------------------------------------------------------------------------
    def destroy(self):
        """Destroy the underlying QWidget object."""
        self._teardown_features()
        focus_registry.unregister(self.widget)
        widget = self.widget
        if widget is not None:
            del self.widget
        super(QtGraphicsItem, self).destroy()
        # If a QWidgetAction was created for this widget, then it has
        # taken ownership of the widget and the widget will be deleted
        # when the QWidgetAction is garbage collected. This means the
        # superclass destroy() method must run before the reference to
        # the QWidgetAction is dropped.
        del self._widget_action

    def parent_widget(self):
        """Reimplemented to only return GraphicsItems"""
        parent = self.parent()
        if parent is not None and isinstance(parent, QtGraphicsItem):
            return parent.widget

    def _teardown_features(self):
        super(QtGraphicsItem, self)._teardown_features()
        self.unhook_item_change()

    def hook_item_change(self):
        widget = self.widget
        widget.itemChange = self.itemChange

    def unhook_item_change(self):
        del self.widget.itemChange

    # --------------------------------------------------------------------------
    # Signals
    # --------------------------------------------------------------------------
    def itemChange(self, change, value):
        widget = self.widget
        if change == QGraphicsItem.ItemPositionHasChanged:
            pos = widget.pos()
            pos = Point(pos.x(), pos.y(), widget.zValue())
            self._guards |= 0x01
            try:
                self.declaration.position = pos
            finally:
                self._guards &= ~0x01
        elif change == QGraphicsItem.ItemSelectedChange:
            self.declaration.selected = widget.isSelected()

        return type(widget).itemChange(widget, change, value)

    # --------------------------------------------------------------------------
    # ProxyGraphicsItem API
    # --------------------------------------------------------------------------
    def set_visible(self, visible):
        self.widget.setVisible(visible)

    def set_enabled(self, enabled):
        self.widget.setEnabled(enabled)

    def set_selectable(self, enabled):
        self.widget.setFlag(QGraphicsItem.ItemIsSelectable, enabled)

    def set_movable(self, enabled):
        self.widget.setFlag(QGraphicsItem.ItemIsMovable, enabled)

    def set_x(self, x):
        if self._guards & 0x01:
            return
        self.widget.setX(x)

    def set_y(self, y):
        if self._guards & 0x01:
            return
        self.widget.setY(y)

    def set_z(self, z):
        if self._guards & 0x01:
            return
        self.widget.setZValue(z)

    def set_position(self, position):
        if self._guards & 0x01:
            return
        pos = self.declaration.position
        w = self.widget
        w.setPos(pos.x, pos.y)
        w.setZValue(pos.z)

    def set_rotation(self, rotation):
        self.widget.setRotation(rotation)

    def set_scale(self, scale):
        self.widget.setScale(scale)

    def set_opacity(self, opacity):
        self.widget.setOpacity(opacity)

    def set_selected(self, selected):
        self.widget.setSelected(selected)

    def set_tool_tip(self, tool_tip):
        self.widget.setToolTip(tool_tip)

    def set_status_tip(self, status_tip):
        self.widget.setToolTip(status_tip)


class QtGraphicsItemGroup(QtGraphicsItem, ProxyGraphicsItemGroup):
    #: Internal widget
    widget = Typed(QGraphicsItemGroup)

    def create_widget(self):
        self.widget = QGraphicsItemGroup(self.parent_widget())

    def init_layout(self):
        super(QtGraphicsItemGroup, self).init_layout()
        widget = self.widget
        for item in self.child_widgets():
            widget.addToGroup(item)

    def child_added(self, child):
        super(QtGraphicsItemGroup, self).child_added(child)
        if isinstance(child, QtGraphicsItem):
            self.widget.addToGroup(child.widget)

    def child_removed(self, child):
        super(QtGraphicsItemGroup, self).child_removed(child)
        if isinstance(child, QtGraphicsItem):
            self.widget.removeFromGroup(child.widget)


class QtGraphicsWidget(QtGraphicsItem, ProxyGraphicsWidget):
    #: Internal widget
    widget = Typed(QGraphicsProxyWidget)

    def create_widget(self):
        """Deferred to the layout pass"""
        pass

    def init_widget(self):
        pass

    def init_layout(self):
        """Create the widget in the layout pass after the child widget has
        been created and intialized. We do this so the child widget does not
        attempt to use this proxy widget as its parent and because
        repositioning must be done after the widget is set.
        """
        self.widget = QGraphicsProxyWidget(self.parent_widget())
        widget = self.widget
        for item in self.child_widgets():
            widget.setWidget(item)
            break
        super(QtGraphicsWidget, self).init_widget()
        super(QtGraphicsWidget, self).init_layout()

    def child_added(self, child):
        super(QtGraphicsItemGroup, self).child_added(child)
        if isinstance(child, QtWidget):
            self.widget.setWidget(child.widget)


class QtAbstractGraphicsShapeItem(QtGraphicsItem, ProxyAbstractGraphicsShapeItem):
    def init_widget(self):
        super(QtAbstractGraphicsShapeItem, self).init_widget()
        d = self.declaration
        if d.pen:
            self.set_pen(d.pen)
        if d.brush:
            self.set_brush(d.brush)

    def set_pen(self, pen):
        if pen:
            self.widget.setPen(get_cached_qpen(pen))
        else:
            self.widget.setPen(QPen())

    def set_brush(self, brush):
        if brush:
            self.widget.setBrush(get_cached_qbrush(brush))
        else:
            self.widget.setBrush(QBrush())


class QtGraphicsLineItem(QtAbstractGraphicsShapeItem, ProxyGraphicsLineItem):
    #: Internal widget
    widget = Typed(QGraphicsLineItem)

    def create_widget(self):
        self.widget = QGraphicsLineItem(self.parent_widget())

    def set_position(self, position):
        self.set_point(self.declaration.point)

    def set_point(self, point):
        pos = self.declaration.position
        self.widget.setLine(pos.x, pos.y, *point[:2])


class QtGraphicsEllipseItem(QtAbstractGraphicsShapeItem, ProxyGraphicsEllipseItem):
    #: Internal widget
    widget = Typed(QGraphicsEllipseItem)

    def create_widget(self):
        self.widget = QGraphicsEllipseItem(self.parent_widget())

    def init_widget(self):
        super(QtGraphicsEllipseItem, self).init_widget()
        d = self.declaration
        self.set_start_angle(d.start_angle)
        self.set_span_angle(d.span_angle)

    def set_position(self, position):
        self.update_rect()

    def set_width(self, width):
        self.update_rect()

    def set_height(self, height):
        self.update_rect()

    def update_rect(self):
        d = self.declaration
        pos = d.position
        self.widget.setRect(pos.x, pos.y, d.width, d.height)

    def set_span_angle(self, angle):
        self.widget.setSpanAngle(int(angle * 16))

    def set_start_angle(self, angle):
        self.widget.setStartAngle(int(angle * 16))


class QtGraphicsRectItem(QtAbstractGraphicsShapeItem, ProxyGraphicsRectItem):
    #: Internal widget
    widget = Typed(QGraphicsRectItem)

    def create_widget(self):
        self.widget = QGraphicsRectItem(self.parent_widget())

    def set_position(self, position):
        self.update_rect()

    def set_width(self, width):
        self.update_rect()

    def set_height(self, height):
        self.update_rect()

    def update_rect(self):
        d = self.declaration
        pos = d.position
        self.widget.setRect(pos.x, pos.y, d.width, d.height)


class QtGraphicsTextItem(QtAbstractGraphicsShapeItem, ProxyGraphicsTextItem):
    #: Internal widget
    widget = Typed(QGraphicsSimpleTextItem)

    def create_widget(self):
        self.widget = QGraphicsSimpleTextItem(self.parent_widget())

    def init_widget(self):
        super(QtGraphicsTextItem, self).init_widget()
        d = self.declaration
        if d.text:
            self.set_text(d.text)
        if d.font:
            self.set_font(d.font)

    def set_text(self, text):
        self.widget.setText(text)

    def set_font(self, font):
        self.widget.setFont(get_cached_qfont(font))


class QtGraphicsPolygonItem(QtAbstractGraphicsShapeItem, ProxyGraphicsPolygonItem):
    #: Internal widget
    widget = Typed(QGraphicsPolygonItem)

    def create_widget(self):
        self.widget = QGraphicsPolygonItem(self.parent_widget())

    def init_widget(self):
        super(QtGraphicsPolygonItem, self).init_widget()
        d = self.declaration
        self.set_points(d.points)

    def set_points(self, points):
        polygon = QPolygonF([QPointF(*p[:2]) for p in points])
        self.widget.setPolygon(polygon)


class QtGraphicsPathItem(QtAbstractGraphicsShapeItem, ProxyGraphicsPathItem):
    #: Internal widget
    widget = Typed(QGraphicsPathItem)

    def create_widget(self):
        self.widget = QGraphicsPathItem(self.parent_widget())

    def init_widget(self):
        super(QtGraphicsPathItem, self).init_widget()
        d = self.declaration
        if d.path:
            self.set_path(d.path)

    def set_path(self, path):
        #: TODO: Convert path
        self.widget.setPath(path)


class QtGraphicsImageItem(QtGraphicsItem, ProxyGraphicsImageItem):
    #: Internal widget
    widget = Typed(QGraphicsPixmapItem)

    def create_widget(self):
        self.widget = QGraphicsPixmapItem(self.parent_widget())

    def init_widget(self):
        super(QtGraphicsImageItem, self).init_widget()
        d = self.declaration
        if d.image:
            self.set_image(d.image)

    def set_image(self, image):
        self.widget.setPixmap(QPixmap.fromImage(get_cached_qimage(image)))