프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / HYTOS / HYTOS / Shapes / EngineeringCalloutTextItem.py @ 498cd3ed

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

1
# coding: utf-8
2
import os.path
3
import copy
4
import sys
5

    
6
try:
7
    from PyQt5.QtCore import Qt, QPointF, QRectF, pyqtSignal, QObject, QT_VERSION_STR, QRect
8
    from PyQt5.QtGui import QImage, QPixmap, QPainterPath, QBrush, QPen, QTransform, QFont, QColor, QFontMetricsF
9
    from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QFileDialog, QGraphicsItem, QAbstractGraphicsShapeItem, \
10
        QGraphicsTextItem
11
except ImportError:
12
    try:
13
        from PyQt4.QtCore import Qt, QRectF, pyqtSignal, QRect, QObject, QT_VERSION_STR
14
        from PyQt4.QtGui import QGraphicsView, QGraphicsScene, QImage, QPixmap, QPainterPath, QFileDialog, QFont, \
15
            QColor, QFontMetricsF
16
    except ImportError:
17
        raise ImportError("ImageViewerQt: Requires PyQt5 or PyQt4.")
18

    
19
from EngineeringPolylineItem import QEngineeringPolylineItem
20
from GraphicsBoundingBoxItem import QGraphicsBoundingBoxItem
21
from AppDocData import *
22
from EngineeringAbstractItem import QEngineeringAbstractItem
23
from TextInfo import TextInfo
24

    
25

    
26
class QEngineeringCalloutTextItem(QGraphicsTextItem, QEngineeringAbstractItem):
27
    lost_focus = pyqtSignal(QGraphicsTextItem)
28
    selected_change = pyqtSignal(QGraphicsItem)
29

    
30
    HIGHLIGHT = '#BC4438'
31
    ZVALUE = 210
32

    
33
    '''
34
        @history    2018.05.17  Jeongwoo    Add self._owner variable
35
    '''
36

    
37
    def __init__(self, uid=None, parent=None):
38
        import uuid
39

    
40
        QGraphicsTextItem.__init__(self, parent)
41
        QEngineeringAbstractItem.__init__(self)
42

    
43
        self.uid = uuid.uuid4() if uid is None else uuid.UUID(uid, version=4)
44
        self.type = 'TEXT'
45
        self.loc = None
46
        self.angle = 0  # angle in radian
47
        self.setFlags(QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable | QGraphicsItem.ItemIsMovable)
48
        self.setAcceptHoverEvents(True)
49
        self.setAcceptTouchEvents(True)
50

    
51
        self._savedColor = None
52
        self.attribute = ''
53

    
54
        self.transfer = Transfer()
55
        self.setZValue(QEngineeringCalloutTextItem.ZVALUE)
56

    
57
    def __str__(self):
58
        """ return string represent uuid """
59
        return str(self.uid)
60

    
61
    '''
62
        @brief  return text string
63
        @author humkyung
64
        @date   2018.04.16
65
    '''
66

    
67
    def text(self):
68
        return self.toPlainText()
69

    
70
    '''
71
        @brief  return center position of text
72
        @author humkyung
73
        @date   2018.04.16
74
    '''
75

    
76
    def center(self):
77
        return self.sceneBoundingRect().center()
78

    
79
    '''
80
        @brief      hover event
81
        @authro     humkyung
82
        @date       
83
    '''
84

    
85
    def hoverEnterEvent(self, event):
86
        self.highlight(True)
87

    
88
    def hoverLeaveEvent(self, event):
89
        self.highlight(False)
90

    
91
    '''
92
        @brief      set highlight
93
        @author     kyouho
94
        @date       2018.08.27
95
    '''
96

    
97
    def highlight(self, flag):
98
        self.hover = flag
99
        if flag:
100
            if self._savedColor is None:
101
                self._savedColor = self.getColor()
102
            #self.setColor(QEngineeringTextItem.HIGHLIGHT)
103
        elif hasattr(self, '_savedColor'):
104
            self.setColor(self._savedColor)
105

    
106
        self.update()
107

    
108
    def hoverMoveEvent(self, event):
109
        pass
110

    
111
    def keyPressEvent(self, event):
112
        try:
113
            if event.key() == Qt.Key_Escape:
114
                self.lost_focus.emit(self)
115
                self.clearFocus()
116

    
117
            super(QEngineeringCalloutTextItem, self).keyPressEvent(event)
118
        except Exception as ex:
119
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
120
                                                           sys.exc_info()[-1].tb_lineno)
121
            self.addMessage.emit(MessageType.Error, message)
122

    
123
    def itemChange(self, change, value):
124
        if change == QGraphicsItem.ItemSelectedChange:
125
            self.selected_change.emit(self)
126
        return value
127

    
128
    def focusOutEvent(self, event):
129
        self.setTextInteractionFlags(Qt.NoTextInteraction)
130
        self.lost_focus.emit(self)
131
        super(QEngineeringCalloutTextItem, self).focusOutEvent(event)
132

    
133
    def mouseDoubleClickEvent(self, event):
134
        if self.textInteractionFlags() == Qt.NoTextInteraction:
135
            self.setTextInteractionFlags(Qt.TextEditorInteraction)
136
            self.setFocus()
137
        super(QEngineeringCalloutTextItem, self).mouseDoubleClickEvent(event)
138

    
139
    def setColor(self, color):
140
        pass
141

    
142
    def highlight(self, flag):
143
        if flag:
144
            self.setDefaultTextColor(QColor(QEngineeringAbstractItem.HOVER_COLOR))
145
        else:
146
            self.setDefaultTextColor(Qt.black)
147

    
148
        self.update()
149

    
150
    def update_label_contents(self):
151
        """build stream no"""
152
        from AppDocData import AppDocData
153
        from EngineeringStreamNoTextItem import QEngineeringStreamNoTextItem
154

    
155
        app_doc_data = AppDocData.instance()
156
        font_size = None
157
        configs = app_doc_data.getAppConfigs('option', 'CalloutFontSize')
158
        if configs and len(configs) == 1:
159
            _font = self.font()
160
            _font.setPointSizeF(float(configs[0].value))
161
            self.setFont(_font)
162

    
163
        configs = app_doc_data.getAppConfigs('option', 'CalloutTextColor')
164
        if configs and len(configs) == 1:
165
            self.setDefaultTextColor(QColor(configs[0].value))
166

    
167
    '''
168
            @brief  override paint(draw connection points)
169
            @author humkyung
170
            @date   2018.07.08
171
        '''
172

    
173
    def paint(self, painter, options=None, widget=None):
174
        super(QEngineeringCalloutTextItem, self).paint(painter, options, widget)
175

    
176
        if self.isSelected():
177
            if not hasattr(self, '_selected_pen'):
178
                self._selected_pen = QPen(Qt.SolidLine)
179
                self._selected_pen.setColor(QColor(255, 0, 0, 127))
180
                self._selected_pen.setWidthF(1)
181
            painter.setPen(self._selected_pen)
182
        else:
183
            if not hasattr(self, '_focuspen'):
184
                self._focuspen = QPen(Qt.SolidLine)
185
                self._focuspen.setColor(Qt.black)
186
                self._focuspen.setWidthF(1.5)
187
            painter.setPen(self._focuspen)
188

    
189
        painter.drawRect(self.boundingRect())
190

    
191
    @staticmethod
192
    def fromDatabase(componentInfos):
193
        """ create a callout from database """
194
        from PlaceCalloutCommand import PlaceCalloutCommand
195

    
196
        item = None
197

    
198
        try:
199
            uid = componentInfos[0]['Comp_UID']  # uid@Components
200
            tag_no = componentInfos[0]['Name']  # name@Components
201
            index = componentInfos[0]['Comp_Index']
202
            dbUid = componentInfos[0]['Symbols_UID']  # Symbol_UID@Components
203
            category = componentInfos[0]['Category']  # Category@SymbolType
204
            _type = componentInfos[0]['Type']  # Type@SymbolType
205
            name = componentInfos[0]['Symbol_Name']  # Name@Symbols
206
            originalPoint = componentInfos[0]['OriginalPoint']  # OriginalPoint@Symbols
207
            x = componentInfos[0]['Comp_X']  # X@Components
208
            y = componentInfos[0]['Comp_Y']  # Y@Components
209
            angle = componentInfos[0]['Rotation']  # Rotation@Components
210
            scale = componentInfos[0]['Scale']  # Scale@Components
211

    
212
            pt = QPointF(float(x), float(y))
213
            item = PlaceCalloutCommand.create_item(pt)
214
            item.setHtml(tag_no)
215
        except Exception as ex:
216
            from App import App
217
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
218
                                                           sys.exc_info()[-1].tb_lineno)
219
            App.mainWnd().addMessage.emit(MessageType.Error, message)
220

    
221
        return item
222

    
223
    def toSql(self):
224
        """convert callout data to sql query"""
225
        from AppDocData import AppDocData
226

    
227
        """ generate sql string to save label to database """
228
        res = []
229

    
230
        try:
231
            cols = ['UID', 'Symbols_UID', 'Name', 'X', 'Y']
232
            values = ['?', "(select uid from Symbols where Name='Callout')", '?', '?', '?']
233

    
234
            param = [str(self.uid), self.toHtml(), self.pos().x(), self.pos().y()]
235
            sql = f"insert or replace into Components({','.join(cols)}) values({','.join(values)})"
236
            res.append((sql, tuple(param)))
237

    
238
            cols, values = ['UID', 'Components_UID', '[Index]', 'X', 'Y'], ['?', '?', '?', '?', '?']
239
            param = [str(self.uid), str(self.uid), 0, self.pos().x(), self.pos().y()]
240
            sql = 'insert or replace into Points({}) values({})'.format(','.join(cols), ','.join(values))
241
            res.append((sql, tuple(param)))
242

    
243
        except Exception as ex:
244
            from App import App
245
            from AppDocData import MessageType
246

    
247
            message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
248
                                                           sys.exc_info()[-1].tb_lineno)
249
            App.mainWnd().addMessage.emit(MessageType.Error, message)
250

    
251
        return res
252

    
253
'''
254
    @brief      The class transfer pyqtSignal Event. Cause Subclass of QGraphicsRectItem can't use pyqtSignal
255
    @author     Jeongwoo
256
    @date       2018.06.18
257
'''
258

    
259

    
260
class Transfer(QObject):
261
    onRemoved = pyqtSignal(QGraphicsItem)
262

    
263
    def __init__(self, parent=None):
264
        QObject.__init__(self, parent)
클립보드 이미지 추가 (최대 크기: 500 MB)