프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / QtImageViewerScene.py @ 702779b0

이력 | 보기 | 이력해설 | 다운로드 (5.4 KB)

1
# coding: utf-8
2
""" This is image viewer scene module """
3

    
4
import sys
5
import os.path
6
from SingletonInstance import SingletonInstance
7

    
8
try:
9
    from PyQt5.QtCore import *
10
    from PyQt5.QtGui import *
11
    from PyQt5.QtWidgets import *
12
except ImportError:
13
    try:
14
        from PyQt4.QtCore import *
15
        from PyQt4.QtGui import *
16
    except ImportError:
17
        raise ImportError("ImageViewerQt: Requires PyQt5 or PyQt4.")
18

    
19
__author__ = "humkyung <humkyung.doftech.co.kr>"
20
__version__ = '1.0.0'
21

    
22

    
23
class QtImageViewerScene(QGraphicsScene):
24
    """ This is image viewer scene class """
25
    contents_changed = pyqtSignal()
26

    
27
    def __init__(self, parent):
28
        QGraphicsScene.__init__(self, parent)
29

    
30
        self._undo_stack = QUndoStack(self)
31
        self._delta = QPointF()
32
        self._pressed_keys = set()
33

    
34
        self.contours = []
35
        self.contour_color = None
36
        self.circles = None
37

    
38
        self.guidesEnabled = False
39
        self._guidePen = QPen()
40
        self._guidePen.setColor(QColor(180, 180, 180))
41
        self._guidePen.setStyle(Qt.DashLine)
42
        self._guidePen.setWidthF(0.3)
43

    
44
    @property
45
    def undo_stack(self):
46
        return self._undo_stack
47

    
48
    def addItem(self, item):
49
        """ add given item to scene """
50

    
51
        QGraphicsScene.addItem(self, item)
52
        self.contents_changed.emit()
53

    
54
    def removeItem(self, item):
55
        """ remove given item from scene """
56
        QGraphicsScene.removeItem(self, item)
57
        self.contents_changed.emit()
58

    
59
    def keyPressEvent(self, event: QKeyEvent):
60
        from SymbolSvgItem import SymbolSvgItem
61
        from EngineeringTextItem import QEngineeringTextItem
62
        from DeleteCommand import DeleteCommand
63

    
64
        try:
65
            if event.key() == Qt.Key_Delete:
66
                cmd = DeleteCommand(self, [item for item in self.selectedItems() if hasattr(item, 'transfer')])
67
                self._undo_stack.push(cmd)
68
            elif event.key() in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right]:
69
                if self.selectedItems():
70
                    items = [text for text in self.selectedItems() if
71
                             issubclass(type(text), QEngineeringTextItem) or issubclass(type(text), SymbolSvgItem)]
72
                    self._pressed_keys.add(event.key())
73
                    if items:
74
                        for item in items:
75
                            item.keyPressEvent(event)
76

    
77
                    modifiers = QApplication.keyboardModifiers()
78
                    delta = 10 if modifiers == Qt.ControlModifier else 1
79
                    if event.key() == Qt.Key_Up:
80
                        self._delta.setY(self._delta.y() - delta)
81
                    elif event.key() == Qt.Key_Down:
82
                        self._delta.setY(self._delta.y() + delta)
83
                    elif event.key() == Qt.Key_Left:
84
                        self._delta.setX(self._delta.x() - delta)
85
                    elif event.key() == Qt.Key_Right:
86
                        self._delta.setX(self._delta.x() + delta)
87

    
88
                    event.accept()
89
                    return
90
            elif event.key() == Qt.Key_Z and event.modifiers() & Qt.ControlModifier:
91
                self._undo_stack.undo()
92
            elif event.key() == Qt.Key_R and event.modifiers() & Qt.ControlModifier:
93
                self._undo_stack.redo()
94

    
95
            super(QtImageViewerScene, self).keyPressEvent(event)
96
        except Exception as ex:
97
            print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
98
                                                       sys.exc_info()[-1].tb_lineno))
99

    
100
    def keyReleaseEvent(self, event: QKeyEvent):
101
        from MoveCommand import MoveCommand
102

    
103
        if event.key() in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right] and not event.isAutoRepeat():
104
            if self.selectedItems() and not self._delta.isNull():
105
                self._undo_stack.push(MoveCommand(self, QPointF(self._delta)))
106
                self._delta.setX(0)
107
                self._delta.setY(0)
108

    
109
        super(QtImageViewerScene, self).keyReleaseEvent(event)
110

    
111
    def clear(self):
112
        """clear undo stack"""
113
        self._undo_stack.clear()
114
        super(QtImageViewerScene, self).clear()
115

    
116
    def drawForeground(self, painter: QPainter, rect: QRectF) -> None:
117
        """draw foreground"""
118
        if self.contours:
119
            pen = QPen(Qt.DotLine)
120
            pen.setColor(Qt.red)
121
            pen.setWidthF(2)
122
            painter.setPen(pen)
123
            for contour in self.contours:
124
                path = QPainterPath()
125
                poly = QPolygonF()
126
                for pt in contour:
127
                    poly.append(QPointF(pt[0], pt[1]))
128
                poly.append(poly[0])
129
                path.addPolygon(poly)
130
                painter.fillPath(path, QBrush(Qt.darkRed if self.contour_color is None else self.contour_color,
131
                                              Qt.SolidPattern))
132

    
133
        if self.circles:
134
            for circle in self.circles:
135
                painter.drawEllipse(circle[0], circle[1], circle[2], circle[2])
136
                pass
137

    
138
        """draw guid line"""
139
        if hasattr(self, 'coords') and self.guidesEnabled:
140
            painter.setClipRect(rect)
141
            painter.setPen(self._guidePen)
142
            painter.drawLine(round(self.coords.x()), round(rect.top()), round(self.coords.x()), round(rect.bottom()))
143
            painter.drawLine(round(rect.left()), round(self.coords.y()), round(rect.right()), round(self.coords.y()))
클립보드 이미지 추가 (최대 크기: 500 MB)