프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / ItemTreeWidget.py @ 2d332169

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

1
# coding: utf-8
2
""" This is item tree widget module """
3

    
4
import os
5
import re
6
import sys
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
from EngineeringAbstractItem import QEngineeringAbstractItem
20
from SymbolSvgItem import SymbolSvgItem
21
from EngineeringTextItem import QEngineeringTextItem
22
from EngineeringNoteItem import QEngineeringNoteItem
23
from EngineeringLineNoTextItem import QEngineeringLineNoTextItem
24
from EngineeringEquipmentItem import QEngineeringEquipmentItem
25
from EngineeringInstrumentItem import QEngineeringInstrumentItem
26
from QEngineeringTrimLineNoTextItem import QEngineeringTrimLineNoTextItem
27
from EngineeringUnknownItem import QEngineeringUnknownItem
28
from EngineeringErrorItem import QEngineeringErrorItem
29
from AppDocData import AppDocData
30
from Drawing import Drawing
31

    
32
class CustomTreeWidgetItem(QTreeWidgetItem):
33
    def __init__(self, *args, **kwargs):
34
        super(CustomTreeWidgetItem, self).__init__(*args, **kwargs)
35

    
36
    def setData(self, column, role, value):
37
        if role == Qt.EditRole:
38
            pass
39
        elif role == Qt.CheckStateRole:
40
            if self.treeWidget() is not None:
41
                state = Qt.CheckState.Unchecked if value is 0 else Qt.CheckState.Checked
42
                self.treeWidget().checkBoxToggled.emit(self, state)
43

    
44
        super(CustomTreeWidgetItem, self).setData(column, role, value)
45

    
46
class QItemTreeWidget(QTreeWidget):
47
    """ This is item tree widget """
48
    TREE_DATA_ROLE = Qt.UserRole
49

    
50
    #Add Signal
51
    singleClicked = pyqtSignal(SymbolSvgItem)
52
    noteNoSingleClicked = pyqtSignal(str, dict)
53
    lineNoSingleClicked = pyqtSignal(QEngineeringAbstractItem)
54
    drawingClicked = pyqtSignal(Drawing)
55
    checkBoxToggled = pyqtSignal(QTreeWidgetItem, Qt.CheckState)
56

    
57
    '''
58
        @history    2018.05.11  Jeongwoo    Add Context Menu settings
59
    '''
60
    def __init__(self, imageViewer):
61
        QTreeWidget.__init__(self)
62

    
63
        self.checkBoxToggled.connect(self.itemCheckBoxToggled)
64

    
65
        self.itemClicked.connect(self.itemClickEvent)
66
        self.imageViewer = imageViewer
67
        self.scene = imageViewer.scene
68
        self.root = None
69
        self.setContextMenuPolicy(Qt.CustomContextMenu)
70
        self.customContextMenuRequested.connect(self.openContextMenu)
71

    
72
    '''
73
        @brief      delete selected symbol
74
        @author     humkyung
75
        @date       2018.07.20
76
    '''
77
    def keyPressEvent(self, event):
78
        try:
79
            if event.key() == Qt.Key_Delete:
80
                if self.selectedItems():
81
                    for item in self.selectedItems():
82
                        data = item.data(0, self.TREE_DATA_ROLE)
83
                        if data is not None:
84
                            self.imageViewer.scene.removeItem(data)
85

    
86
                            if type(data) is QEngineeringLineNoTextItem:
87
                                self.imageViewer.mainWindow.removedItems['LINE'].append(str(data.uid))
88
                            elif type(data) is QEngineeringInstrumentItem:
89
                                self.imageViewer.mainWindow.removedItems['INST'].append(str(data.uid))
90
                            elif type(data) is QEngineeringEquipmentItem:
91
                                self.imageViewer.mainWindow.removedItems['EQUIP'].append(str(data.uid))
92
                            elif type(data) is QEngineeringNoteItem:
93
                                self.imageViewer.mainWindow.removedItems['NOTE'].append(str(data.uid))
94

    
95
                            item.parent().removeChild(item)
96
                event.accept()
97
            elif event.key() == Qt.Key_Up:
98
                if self.selectedItems():
99
                    item = self.selectedItems()[0]
100
                    aboveItem = self.itemAbove(item)
101
                    if aboveItem is not None:
102
                        self.setCurrentItem(aboveItem)
103
                        self.scrollToItem(aboveItem, QAbstractItemView.EnsureVisible)
104
                        self.itemClickEvent(aboveItem, 0)
105
                event.accept()
106
            elif event.key() == Qt.Key_Down:
107
                if self.selectedItems():
108
                    item = self.selectedItems()[0]
109
                    belowItem = self.itemBelow(item)
110
                    if belowItem is not None:
111
                        self.setCurrentItem(belowItem)
112
                        self.scrollToItem(belowItem, QAbstractItemView.EnsureVisible)
113
                        self.itemClickEvent(belowItem, 0)
114
                event.accept()
115
            else:
116
                event.ignore()
117
        except Exception as ex:
118
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
119

    
120
    '''
121
        @brief      Show Context Menu
122
        @author     Jeongwoo
123
        @date       18.05.11
124
        @history    18.06.14    Jeongwoo    Add item None check
125
                    humkyung 2018.06.27 add menu of run item for selecting line type
126
    '''
127
    def openContextMenu(self, position):
128
        from EngineeringRunItem import QEngineeringRunItem
129

    
130
        indexes = self.selectedIndexes()
131
        itemPosition = self.mapTo(self, position)
132
        item = self.itemAt(itemPosition)
133
        if item is not None:
134
            data = item.data(0, self.TREE_DATA_ROLE)
135
            if len(indexes) > 0 and data is not None and issubclass(type(data), QEngineeringLineNoTextItem):
136
                index = indexes[0]
137
                menu = QMenu()
138
                pickColorAction = QAction(self.tr("Select Line Color"))
139
                pickColorAction.triggered.connect(lambda : self.pickColorClickEvent(item))
140
                menu.addAction(pickColorAction)
141
                explode_action = QAction(self.tr("Explode"))
142
                explode_action.triggered.connect(lambda : self.explode_line_no(item))
143
                menu.addAction(explode_action)
144
                menu.exec_(self.viewport().mapToGlobal(position))
145
            elif len(indexes) > 0 and data is not None and issubclass(type(data), QEngineeringRunItem):
146
                index = indexes[0]
147
                menu = QMenu()
148
                lineTypeAction = QAction(self.tr("Select Line Type"))
149
                lineTypeAction.triggered.connect(lambda : self.lineTypeClickEvent(item))
150
                menu.addAction(lineTypeAction)
151
                menu.exec_(self.viewport().mapToGlobal(position))
152

    
153
    '''
154
        @brief      Pick Color for Line No
155
        @author     Jeongwoo
156
        @date       18.05.11
157
        @history    18.05.14    Jeongwoo    Change method to change color by changeTreeWidgetItemColorRecursively()
158
    '''
159
    def pickColorClickEvent(self, lineNoTreeWidgetItem):
160
        color = QColorDialog.getColor() # Dialog returns QColor
161
        
162
        if color is not None:
163
            lineNoTreeWidgetItem.setForeground(0, QBrush(color))
164
            lineNoTreeWidgetItem.setFont(0, lineNoTreeWidgetItem.font(0))
165
            lineNoItem = lineNoTreeWidgetItem.data(0, self.TREE_DATA_ROLE)
166
            if lineNoItem:
167
                lineNoItem.change_color(color.name())
168
                lineNoItem.setColor(color.name())
169
                connectedItems = lineNoItem.getConnectedItems()
170
                if connectedItems is not None:
171
                    for connectedItem in connectedItems:
172
                        connectedItem.setColor(color.name())
173
                    self.changeTreeWidgetItemColorRecursively(lineNoTreeWidgetItem, color)
174

    
175
    def explode_line_no(self, lineNoTreeWidgetItem):
176
        """ explode line no """
177

    
178
        try:
179
            line_no_item = lineNoTreeWidgetItem.data(0, self.TREE_DATA_ROLE)
180
            if line_no_item:
181
                connected_items = line_no_item.getConnectedItems()
182
                for item in connected_items:
183
                    self.addTreeItem(self.SymbolsTreeItem, item)
184

    
185
                for i in reversed(range(lineNoTreeWidgetItem.childCount())):
186
                    lineNoTreeWidgetItem.takeChild(i)
187

    
188
                line_no_item.explode()
189
        finally:
190
            pass
191

    
192
    '''
193
        @brief      pick line type
194
        @author     humkyung 
195
        @date       2018.06.27
196
    '''
197
    def lineTypeClickEvent(self, item):
198
        pass
199

    
200
    '''
201
        @brief      Change Color recursively
202
        @author     Jeongwoo
203
        @date       18.05.14
204
    '''
205
    def changeTreeWidgetItemColorRecursively(self, item, color):
206
        for index in range(item.childCount()):
207
            child = item.child(index)
208
            child.setForeground(0, QBrush(color))
209
            child.setFont(0, child.font(0))
210
            self.changeTreeWidgetItemColorRecursively(child, color)
211

    
212
    '''
213
        @brief      Clear TreeWidget and Set Current PID
214
        @author     Jeongwoo
215
        @date       18.04.11
216
        @history    2018.04.26  Jeongwoo    Add Child [SYMBOLS, NOTES] into root item
217
                    2018.05.09  Jeongwoo    Change method to add default tree items
218
                    humkyung 2018.06.10 add tree item for Line No and Unknown Item
219
    '''
220
    def setCurrentPID(self, drawingName):
221
        appDocData = AppDocData.instance()
222

    
223
        self.clear()
224
        self.root = QTreeWidgetItem(self, [drawingName])
225
        self.root.setIcon(0, QIcon(':newPrefix/objects.png'))
226
        self.root.setData(0, self.TREE_DATA_ROLE, appDocData.activeDrawing)
227
        child = self.root.addChild(QTreeWidgetItem(['LINE NO']))
228
        self.root.child(self.root.childCount() - 1).setFlags(self.root.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
229
        self.root.child(self.root.childCount() - 1).setCheckState(0, Qt.Checked)
230
        self.LineNoTreeItem = self.root.child(self.root.childCount() - 1)
231
        self.root.addChild(QTreeWidgetItem(['EQUIPMENTS']))
232
        self.EqpTreeItem = self.root.child(self.root.childCount() - 1)
233
        self.root.addChild(QTreeWidgetItem(['SYMBOLS']))
234
        self.SymbolsTreeItem = self.root.child(self.root.childCount() - 1)
235
        self.root.addChild(QTreeWidgetItem(['NOTES']))
236
        self.NotesTreeItem = self.root.child(self.root.childCount() - 1)
237
        self.root.addChild(QTreeWidgetItem(['UNKNOWN']))
238
        self.UnknownTreeItem = self.root.child(self.root.childCount() - 1)
239

    
240
        for idx in range(self.root.childCount()):
241
            child = self.root.child(idx)
242
            child.setIcon(0, QIcon(':newPrefix/folder-black.png'))
243

    
244
    '''
245
        @brief  create tree item for pipe run if need
246
        @author humkyung
247
        @date   2018.05.15
248
        @history    2018.05.17  Jeongwoo    Change run item color with parent(LineNo Item) color
249
    '''
250
    def addPipeRunTreeItemIfNeed(self, lineNoTreeItem, pipeRun):
251
        for index in range(lineNoTreeItem.childCount()):
252
            treeItem = lineNoTreeItem.child(index)
253
            itemData = treeItem.data(0, self.TREE_DATA_ROLE)
254
            if itemData is not None and itemData == pipeRun:
255
                return treeItem
256

    
257
        runItem = QTreeWidgetItem(['RUNS {}'.format(lineNoTreeItem.childCount()+1)])
258
        runItem.setData(0, self.TREE_DATA_ROLE, pipeRun)
259

    
260
        brush = lineNoTreeItem.foreground(0)
261
        runItem.setForeground(0, brush)
262
        runItem.setFont(0, runItem.font(0))
263

    
264
        lineNoTreeItem.addChild(runItem)
265

    
266
        return runItem
267

    
268
    '''
269
        @brief      add a tree item
270
        @author     humkyung
271
        @date       2018.04.17
272
        @history    humkyung 2018.04.19 treat a case parent is changed
273
                    Jeongwoo 2018.04.26 QEngineeringTextItem → QEngineeringLineNoTextItem
274
                                        Insert if-statement for QEngineeringNoteItem
275
                                        Add if-statement for QEngineeringLineNoTextItem
276
                    Jeongwoo 2018.05.11 Set color when SymbolSvgItem moved into new parent(Line No)
277
                    Jeongwoo 2018.05.15 Add break keyword on if-statement
278
                    Jeongwoo 2018.05.17 Set TreeWidgetItem's color with data's color And Set Data's color on LineNoTextItem Setting
279
                    humkyung 2018.06.12 add unknown item
280
                    humkyung 2018.07.20 append nozzle to equipment
281
    '''
282
    def addTreeItem(self, parent, child):
283
        item = None
284
        appDocData = AppDocData.instance()
285

    
286
        try:
287
            if (not hasattr(child, 'treeItem')) or (child.treeItem is None):
288
                if issubclass(type(child), SymbolSvgItem):
289
                    isEquipmentType = appDocData.isEquipmentType(child.type)
290
                    if isEquipmentType:
291
                        item = QTreeWidgetItem(self.EqpTreeItem, [child.name])
292
                        item.setData(0, self.TREE_DATA_ROLE, child)
293
                    elif child.type == 'Nozzles':
294
                        for i in range(self.EqpTreeItem.childCount()):
295
                            eqpTreeItem = eqpRootTreeItem[0].child(i)
296
                            eqpSymbol = eqpTreeItem.data(0, self.TREE_DATA_ROLE)
297
                            if child.owner is eqpSymbol:
298
                                symbolsRootItem = eqpTreeItem
299
                                item = QTreeWidgetItem(eqpTreeItem, [child.name])
300
                                item.setData(0, self.TREE_DATA_ROLE, child)
301
                                break
302
                        
303
                        if item is None:
304
                            item = QTreeWidgetItem(self.SymbolsTreeItem, [child.name])
305
                    elif child.type == 'Notes':
306
                        return item
307
                    else:
308
                        item = QTreeWidgetItem(self.SymbolsTreeItem, [child.name])
309
                    
310
                    if item is not None:
311
                        iconPath = os.path.join(AppDocData.instance().getCurrentProject().getSvgFilePath(), child.type , child.name + ".svg")
312
                        item.setIcon(0, QIcon(iconPath))
313
                        item.setData(0, self.TREE_DATA_ROLE, child)
314
                        brush = QBrush()
315
                        brush.setColor(QColor(child.getColor()))
316
                        item.setForeground(0, brush)
317
                        item.setFont(0, item.font(0))
318
                        child.treeItem = item
319
                        if isEquipmentType:
320
                            self.EqpTreeItem.addChild(item)
321
                            self.EqpTreeItem.sortChildren(0, Qt.AscendingOrder)  # sort childrens
322
                        else:
323
                            self.SymbolsTreeItem.addChild(item)
324
                            self.SymbolsTreeItem.sortChildren(0, Qt.AscendingOrder)  # sort childrens
325
                elif type(child) is QEngineeringLineNoTextItem:
326
                    item = CustomTreeWidgetItem([child.text()])
327
                    item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
328
                    item.setData(0, self.TREE_DATA_ROLE, child)
329
                    item.setCheckState(0, Qt.Checked if child.isVisible() else Qt.Unchecked)
330
                    brush = QBrush()
331
                    brush.setColor(QColor(child.getColor()))
332
                    item.setForeground(0, brush)
333
                    item.setFont(0, item.font(0))
334
                    child.treeItem = item
335
                    self.LineNoTreeItem.addChild(item)
336
                elif type(child) is QEngineeringTrimLineNoTextItem:
337
                    item = CustomTreeWidgetItem(['Unknown Line'])
338
                    item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
339
                    item.setData(0, self.TREE_DATA_ROLE, child)
340
                    item.setCheckState(0, Qt.Checked if child.isVisible() else Qt.Unchecked)
341
                    brush = QBrush()
342
                    brush.setColor(QColor(child.getColor()))
343
                    item.setForeground(0, brush)
344
                    item.setFont(0, item.font(0))
345
                    child.treeItem = item
346
                    self.LineNoTreeItem.addChild(item)
347
                elif (type(child) is QEngineeringNoteItem):
348
                    founds = None
349
                    for i in range(self.NotesTreeItem.childCount()):
350
                        item = self.NotesTreeItem.child(i)
351
                        notes = item.data(0, self.TREE_DATA_ROLE)
352
                        founds = [note for note in notes if note.text() == child.text()]
353
                        if founds: break
354

    
355
                    if founds:
356
                        item.setData(0, self.TREE_DATA_ROLE, founds + [child, ])
357
                    else:
358
                        item = QTreeWidgetItem([child.text()])
359
                        item.setData(0, self.TREE_DATA_ROLE, [child, ])
360
                        if parent is not None:
361
                            parent.addChild(item)
362
                            parent.sortChildren(0, Qt.AscendingOrder)  # sort childrens
363
                    child.treeItem = item
364
                    item.setText(0, '{}({})'.format(child.text(), len(item.data(0, self.TREE_DATA_ROLE))))
365

    
366
                    # show note icon if note icon is setted
367
                    if child.symbol:
368
                        iconPath = os.path.join(appDocData.getCurrentProject().getSvgFilePath(), 'Notes' , child.symbol.name + '.svg')
369
                        item.setIcon(0, QIcon(iconPath))
370
                elif (type(child) is QEngineeringUnknownItem):
371
                    item = QTreeWidgetItem(['Unknown'])
372
                    item.setData(0, self.TREE_DATA_ROLE, child)
373
                    child.treeItem = item
374
                    self.UnknownTreeItem.addChild(item)
375
                    if child.lineIndicator == 'Match':
376
                        item.setHidden(True)
377
            elif issubclass(type(child), SymbolSvgItem):  # change item's parent
378
                foundItems = self.findItems(child.name, Qt.MatchExactly|Qt.MatchRecursive, 0)
379
                if foundItems is not None:
380
                    for item in foundItems:
381
                        data = item.data(0, self.TREE_DATA_ROLE)
382
                        if data is not None and (data == child) and (parent is not item.parent()):
383
                            parentData = parent.data(0, self.TREE_DATA_ROLE)
384
                            if parentData is not None and issubclass(type(parentData), QEngineeringLineNoTextItem):
385
                                for index in range(len(parentData.runs)):
386
                                    runGroup = parentData.runs[index]
387
                                    if data in runGroup.items:
388
                                        item.parent().removeChild(item) # remove item from original parent
389
                                        runItem = self.addPipeRunTreeItemIfNeed(parent, runGroup) #parent.child(index)
390
                                        brush = QBrush()
391
                                        brush.setColor(QColor(item.data(0, self.TREE_DATA_ROLE).getColor()))
392
                                        item.setForeground(0, brush)
393
                                        #item.data(0, self.TREE_DATA_ROLE).setColor(brush.color().name())
394
                                        item.setFont(0, item.font(0))
395
                                        runItem.addChild(item)
396
                                        break
397
                                    else:
398
                                        pass
399
                            elif parent is not None:
400
                                item.parent().removeChild(item) # remove item from original parent
401
                                parent.addChild(item)
402
                            break
403
            elif type(child) is QEngineeringLineNoTextItem:
404
                foundItems = self.findItems(child.text(), Qt.MatchExactly|Qt.MatchRecursive, 0)
405
                if foundItems is not None:
406
                    for item in foundItems:
407
                        data = item.data(0, self.TREE_DATA_ROLE)
408
                        if data is not None and (data == child):
409
                            connectedItems = data.getConnectedItems()
410
                            color = data.getColor()
411
                            for connectedItem in connectedItems:
412
                                connectedItem.setColor(color)
413
                            return item
414
        except Exception as ex:
415
            from App import App
416
            from AppDocData import MessageType
417

    
418
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
419
            App.mainWnd().addMessage.emit(MessageType.Error, message)
420

    
421
        return item
422

    
423
    '''
424
        @brief      Scene Changed Listener
425
        @author     Jeongwoo
426
        @date       18.04.11
427
        @history    Jeongwoo 2018.04.25 Add QEngineeringNoteItem to list for loop  / NOT QEngineeringTextItem
428
                    Jeongwoo 2018.04.26 Change changedSceneItems conditions in loop (QEngineeringTextItem → QEngineeringLineNoTextItem)
429
                    humkyung 2018.07.20 put items which's owner is None before item which's owner is not None
430
    '''
431
    lastSceneItems = None
432
    def sceneChanged(self, sceneItems):
433
        try:
434
            changedSceneItems = [item for item in sceneItems if ((issubclass(type(item), SymbolSvgItem) and type(item) is not QEngineeringErrorItem) or (type(item) is QEngineeringNoteItem) or (type(item) is QEngineeringLineNoTextItem) 
435
                                or (type(item) is QEngineeringUnknownItem)) and (not hasattr(item, 'treeItem') or item.treeItem is None)] # Sublist includes SymbolSvgItem
436
            first = [item for item in changedSceneItems if item.owner is None]
437
            second = [item for item in changedSceneItems if item.owner is not None]
438
            if first + second: self.initResultTreeWidget(first + second)
439
        finally:
440
            self.update_item_count()
441

    
442
    '''
443
        @brief      Initialize TreeWidget
444
                    Tree Item Clear and Add Item
445
        @author     Jeongwoo
446
        @date       2018.04.11
447
        @history    2018.04.12 Jeongwoo    Declare self.TREE_DATA_ROLE for QTreeWidgetItem.data(column, role)
448
        @history    2018.04.17 humkyung NOT remove child of root
449
                    2018.04.25 Jeongwoo     Add QEngineeringNoteItem Child
450
                    2018.04.26 Jeongwoo     Change method to insert child
451
    '''
452
    def initResultTreeWidget(self, items):
453
        for item in items:
454
            if (type(item) is QEngineeringNoteItem):
455
                self.addTreeItem(self.NotesTreeItem, item)
456
            else:
457
                self.addTreeItem(self.root, item)
458
                    
459
        if self.NotesTreeItem is not None:
460
            self.NotesTreeItem.sortChildren(0, Qt.AscendingOrder)
461

    
462
        self.expandAll()
463
        
464
    def itemCheckBoxToggled(self, item, checkState):
465
        """
466
        set visible of invisible of item
467
        """
468
        try:
469
            itemData = item.data(0, self.TREE_DATA_ROLE)   
470
            if (type(itemData) is QEngineeringLineNoTextItem) or (type(itemData) is QEngineeringTrimLineNoTextItem):
471
                itemData.setVisible(checkState == Qt.CheckState.Checked)
472
        except Exception as ex:
473
            from App import App
474
            from AppDocData import MessageType
475

    
476
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
477
            App.mainWnd().addMessage.emit(MessageType.Error, message)
478
        finally:
479
            pass
480

    
481
    '''
482
        @brief      TreeWidget Item click listener
483
        @author     Jeongwoo
484
        @date       18.04.11
485
        @history    18.04.12    Jeongwoo    Declare self.TREE_DATA_ROLE for QTreeWidgetItem.data(column, role)
486
                    18.04.13    Jeongwoo    Signal 'singleClicked' emit SymbolSvgItem
487
                                            CenterOn() with Symbol's center
488
                    18.04.25    Jeongwoo    Add QEngineeringNoteItem Click event
489
                    18.04.26    Jeongwoo    QEngineeringTextItem → QEngineeringLineNoTextItem
490
                    18.04.27    Jeongwoo    Find NOTE Contents when NOTE No. Clicked
491
                                            Move singClicked to if-statement type(itemData) is SymbolSvgItem:
492
                    18.05.10    Jeongwoo    Add lineNoSingleClicked emit
493
                    humkyung 2018.07.07 emit singleClicked signal when user click drawing name
494
    '''
495
    def itemClickEvent(self, item, columnNo, isSvgClick = False):
496
        from Drawing import Drawing
497
        from EngineeringRunItem import QEngineeringRunItem
498
        from HighlightCommand import HighlightCommand
499

    
500
        hilightColor = QColor(255, 0, 0, 127)
501

    
502
        itemData = item.data(0, self.TREE_DATA_ROLE)
503
        
504
        if itemData is not None: ## Not PID Name
505
            if issubclass(type(itemData), SymbolSvgItem):
506
                HighlightCommand(self.imageViewer).execute(itemData)
507
                ## Draw rectangle on selected symbol
508
                #rect = itemData.sceneBoundingRect()
509
                #if isSvgClick == False:
510
                #    self.imageViewer.centerOn(rect.center())
511
                ## Send new event to imageViewer's zoomImage Method
512
                #self.imageViewer.zoomImage(True, QMouseEvent(QEvent.MouseButtonPress, self.imageViewer.mapFromScene(QPointF(rect.left(), rect.top())), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier), 3)
513

    
514
                self.singleClicked.emit(itemData)
515
            elif (type(itemData) is QEngineeringLineNoTextItem) or (type(itemData) is QEngineeringRunItem):
516
                HighlightCommand(self.imageViewer).execute(itemData)
517
                self.lineNoSingleClicked.emit(itemData)
518
                for child in range(item.childCount()):
519
                    item.child(child).setSelected(True)
520
            elif type(itemData) is list and type(itemData[0]) is QEngineeringNoteItem:
521
                HighlightCommand(self.imageViewer).execute(itemData)
522
                '''
523
                rect = itemData.sceneBoundingRect()
524
                if isSvgClick == False:
525
                    self.imageViewer.centerOn(rect.center())
526
                ## Send new event to imageViewer's zoomImage Method
527
                self.imageViewer.zoomImage(True, QMouseEvent(QEvent.MouseButtonPress, self.imageViewer.mapFromScene(QPointF(rect.left(), rect.top())), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier), 3)
528
                '''
529
                noteContentsList = itemData[0].findNoteContents(itemData[0].text())
530

    
531
                self.noteNoSingleClicked.emit(itemData[0].text(), noteContentsList)
532
            elif type(itemData) is QEngineeringUnknownItem:
533
                HighlightCommand(self.imageViewer).execute(itemData)
534
            elif type(itemData) is Drawing:
535
                self.drawingClicked.emit(itemData)
536
                
537
            '''
538
            if issubclass(type(itemData), QGraphicsItem):
539
                itemData.setSelected(True)
540
                itemData.update()
541
            '''
542

    
543
    '''
544
        @brief  find item which has data is given item
545
        @author humkyung
546
        @date   2018.04.23
547
        @history    2018.06.18  Jeongwoo    Add if-statement for QEngineeringUnknownItem
548
        @history    2018.11.22  euisung     add delete note
549
    '''
550
    def findItemByData(self, item):
551
        if issubclass(type(item), SymbolSvgItem):
552
            foundItems = self.findItems(item.name, Qt.MatchExactly|Qt.MatchRecursive, 0)
553
            for foundItem in foundItems:
554
                data = foundItem.data(0, self.TREE_DATA_ROLE)
555
                if data is not None and data is item:
556
                    return foundItem
557
        elif type(item) is QEngineeringLineNoTextItem:
558
            foundItems = self.findItems(item.text() , Qt.MatchExactly|Qt.MatchRecursive, 0)
559
            for foundItem in foundItems:
560
                data = foundItem.data(0, self.TREE_DATA_ROLE)
561
                if data is not None and data is item:
562
                    return foundItem
563
        elif type(item) is QEngineeringUnknownItem:
564
            foundItems = self.findItems('Unknown' , Qt.MatchExactly|Qt.MatchRecursive, 0)
565
            for foundItem in foundItems:
566
                data = foundItem.data(0, self.TREE_DATA_ROLE)
567
                if data is not None and data is item:
568
                    return foundItem
569
        elif type(item) is QEngineeringNoteItem:
570
            foundItems = self.findItems(item.text() , Qt.MatchExactly|Qt.MatchRecursive, 0)
571
            for foundItem in foundItems:
572
                data = foundItem.data(0, self.TREE_DATA_ROLE)
573
                if data is not None and data is item:
574
                    return foundItem
575
        
576
        return None
577

    
578
    '''
579
        @brief  Init LineNoItems child
580
        @author kyouho
581
        @date   2018.09.17
582
    '''
583
    def InitLineNoItems(self):
584
        try: 
585
            removeLineItem = []
586
            for lineIndex in range(self.LineNoTreeItem.childCount()):
587
                ## LineNoItem, TrimLine Item
588
                lineItem = self.LineNoTreeItem.child(lineIndex)
589

    
590
                removeRunItem = []
591
                for runIndex in range(lineItem.childCount()):
592
                    ## RUN Item
593
                    runItem = lineItem.child(runIndex)
594
                    for symbolIndex in range(runItem.childCount()):
595
                        symbolItem = runItem.child(0)
596
                        symbol = symbolItem.data(0, self.TREE_DATA_ROLE)
597

    
598
                        symbolItem.parent().removeChild(symbolItem)
599

    
600
                        if AppDocData.instance().isEquipmentType(symbol.type):
601
                            self.EqpTreeItem.addChild(symbolItem)
602
                        else:
603
                            self.SymbolsTreeItem.addChild(symbolItem)
604

    
605
                    ## 지울 Item 모음
606
                    removeRunItem.append(runItem)
607
                ## Run Item들 삭제
608
                for removeItem in removeRunItem:
609
                    lineItem.removeChild(removeItem)
610
                ## 지울 Trim Line 모음
611
                if lineItem.text(0) == 'Trim Line':
612
                    removeLineItem.append(lineItem)
613
            ## Trim Line들 삭제
614
            for removeItem in removeLineItem:
615
                self.LineNoTreeItem.removeChild(removeItem)
616

    
617
        except Exception as ex:
618
            from App import App
619
            from AppDocData import MessageType
620

    
621
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
622
            App.mainWnd().addMessage.emit(MessageType.Error, message)
623

    
624
    '''
625
        @brief      Find QTreeWidgetItem by SymbolSvgItem object
626
        @author     Jeongwoo
627
        @date       18.04.11
628
        @history    18.04.12    Jeongwoo    Change Flags (Qt.MatchExactly → Qt.MatchExactly|Qt.MatchRecursive)
629
                                            Declare self.TREE_DATA_ROLE for QTreeWidgetItem.data(column, role)
630
        @history    2018.11.22  euisung     add note, unknown
631
    '''
632
    @pyqtSlot(SymbolSvgItem)
633
    def findItem(self, item):
634
        if issubclass(type(item), SymbolSvgItem):
635
            foundItems = self.findItems(item.name, Qt.MatchExactly|Qt.MatchRecursive, 0)
636
            if foundItems is not None:
637
                for fItem in foundItems:
638
                    data = fItem.data(0, self.TREE_DATA_ROLE)
639
                    if data is not None and data == item:
640
                        self.setCurrentItem(fItem)
641
                        return
642
        elif type(item) is QEngineeringLineNoTextItem:
643
            foundItems = self.findItems(item.text(), Qt.MatchExactly|Qt.MatchRecursive, 0)
644
            if foundItems is not None:
645
                for fItem in foundItems:
646
                    data = fItem.data(0, self.TREE_DATA_ROLE)
647
                    if data is not None and data == item:
648
                        self.setCurrentItem(fItem)
649
                        return
650
        elif type(item) is QEngineeringNoteItem:
651
            founds = None
652
            for i in range(self.NotesTreeItem.childCount()):
653
                child = self.NotesTreeItem.child(i)
654
                notes = child.data(0, self.TREE_DATA_ROLE)
655
                founds = [note for note in notes if note.text() == item.text()]
656
                if founds:
657
                    self.setCurrentItem(child)
658
                    return
659
        elif type(item) is QEngineeringUnknownItem:
660
            foundItems = self.findItems('Unknown', Qt.MatchExactly|Qt.MatchRecursive, 0)
661
            if foundItems is not None:
662
                for fItem in foundItems:
663
                    data = fItem.data(0, self.TREE_DATA_ROLE)
664
                    if data is not None and data == item:
665
                        self.setCurrentItem(fItem)
666
                        return
667

    
668
        ## Not found
669
        msg = QMessageBox()
670
        msg.setIcon(QMessageBox.Warning)
671
        msg.setText('선택하신 심볼의 데이터를 찾을 수 없습니다.')
672
    
673
    '''
674
        @brief      remove given item
675
        @author     humkyung
676
        @date       2018.04.23
677
        @history    Jeongwoo 2018.05.25 Remove Highlighting when item removed
678
                    humkyung 2018.07.22 removed code to Remove highlighting
679
    '''
680
    @pyqtSlot(QGraphicsItem)
681
    def itemRemoved(self, item):
682
        try:
683
            foundItem = self.findItemByData(item)
684
            if foundItem is not None:
685
                foundItem.parent().removeChild(foundItem)
686
        finally:
687
            self.update_item_count()
688

    
689
    def update_item_count(self):
690
        """
691
        update items count
692
        """
693
        if hasattr(self, 'LineNoTreeItem'):
694
            self.LineNoTreeItem.setText(0, 'LINE NO({})'.format(self.LineNoTreeItem.childCount()))
695
        if hasattr(self, 'EqpTreeItem'):
696
            self.EqpTreeItem.setText(0, 'EQUIPMENTS({})'.format(self.EqpTreeItem.childCount()))
697
        if hasattr(self, 'SymbolsTreeItem'):
698
            self.SymbolsTreeItem.setText(0, 'SYMBOLS({})'.format(self.SymbolsTreeItem.childCount()))
699
        if hasattr(self, 'NotesTreeItem'):
700
            self.NotesTreeItem.setText(0, 'NOTES({})'.format(self.NotesTreeItem.childCount()))
701
        if hasattr(self, 'UnknownTreeItem'):
702
            self.UnknownTreeItem.setText(0, 'UNKNOWN({})'.format(self.UnknownTreeItem.childCount()))
클립보드 이미지 추가 (최대 크기: 500 MB)