프로젝트

일반

사용자정보

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

hytos / DTI_PID / DTI_PID / LibraryItem.py @ 85ba4667

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

1
# -*- coding: utf-8 -*-
2
""" This is library module """
3

    
4
import sys
5
from PyQt5.QtCore import *
6
from PyQt5.QtGui import *
7
from PyQt5.QtWidgets import *
8
from PyQt5.QtSvg import *
9
from AppDocData import AppDocData, MessageType
10

    
11

    
12
class LibraryItemWidget(QWidget):
13
    COLUMN = 3
14

    
15
    def __init__(self, symbol_tree_widget, parent=None):
16
        super().__init__(parent)
17
        try:
18
            self.setAcceptDrops(True)
19
            self._symbol_tree_widget = symbol_tree_widget
20

    
21
            self.layout = QGridLayout()
22
            self.setLayout(self.layout)
23

    
24
            app_doc_data = AppDocData.instance()
25
            self.favorites = app_doc_data.get_favorite_libraries()
26

    
27
            for idx, symbol in enumerate(self._symbol_tree_widget.symbols):
28
                matches = [favorite for favorite in self.favorites if symbol.getUid() == favorite['Symbol_UID']]
29
                if matches:
30
                    self.layout.addWidget(LibraryItem(symbol), int(idx / LibraryItemWidget.COLUMN),
31
                                          idx % LibraryItemWidget.COLUMN)
32
        except Exception as ex:
33
            from App import App
34

    
35
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
36
                                                           sys.exc_info()[-1].tb_lineno)
37
            App.mainWnd().addMessage.emit(MessageType.Error, message)
38

    
39
    def remove_library(self, item):
40
        """remove library from widget and delete it from database"""
41
        matches = [idx for idx in range(self.layout.count()) if self.layout.itemAt(idx).widget() is item]
42
        if matches:
43
            app_doc_data = AppDocData.instance()
44
            with app_doc_data.project.database.connect() as conn:
45
                try:
46
                    cursor = conn.cursor()
47
                    sql = 'delete from Libraries where Symbol_UID=?'
48
                    param = (str(item.symbol.getUid()), )
49
                    cursor.execute(sql, param)
50
                    conn.commit()
51

    
52
                    layout_item = self.layout.takeAt(matches[0])
53
                    self.layout.removeWidget(item)
54
                    item.deleteLater()
55
                    del item
56
                    self.layout.removeItem(layout_item)
57
                    del layout_item
58

    
59
                    self.layout.update()
60
                except Exception as ex:
61
                    print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
62
                                                               sys.exc_info()[-1].tb_lineno))
63

    
64
    def add_library(self, item):
65
        """add library to widget and save it"""
66
        import os
67
        import uuid
68

    
69
        row = int((self.layout.count()) / LibraryItemWidget.COLUMN)
70
        col = (self.layout.count()) % LibraryItemWidget.COLUMN
71
        self.layout.addWidget(item, row, col)
72

    
73
        app_doc_data = AppDocData.instance()
74
        with app_doc_data.project.database.connect() as conn:
75
            try:
76
                cursor = conn.cursor()
77
                sql = 'insert into Libraries(UID,User,Symbol_UID) values(?,?,?)'
78
                param = (str(uuid.uuid4()), os.environ['COMPUTERNAME'].upper(), item.symbol.getUid())
79
                cursor.execute(sql, param)
80
                conn.commit()
81
            except Exception as ex:
82
                print('error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
83
                                                          sys.exc_info()[-1].tb_lineno))
84

    
85
    def dragEnterEvent(self, event: QDragEnterEvent) -> None:
86
        if issubclass(type(event.source()), QTreeWidget) and event.mimeData().hasFormat('text/plain'):
87

    
88
            # check if symbol is already registered
89
            for idx in range(self.layout.count()):
90
                widget = self.layout.itemAt(idx).widget()
91
                id = f"{event.mimeData().tag.getType()}.{event.mimeData().tag.getName()}"
92
                if widget.id == id:
93
                    event.ignore()
94
                    return
95
            # up to here
96
            event.accept()
97
        else:
98
            event.ignore()
99

    
100
    def dropEvent(self, event: QDropEvent) -> None:
101
        if hasattr(event.mimeData(), 'tag'):
102
            item = LibraryItem(event.mimeData().tag)
103
            self.add_library(item)
104

    
105
            event.acceptProposedAction()
106

    
107

    
108
class LibraryItem(QFrame):
109
    def __init__(self, symbol):
110
        QFrame.__init__(self)
111
        self.id = f"{symbol.getType()}.{symbol.getName()}"
112
        self._symbol = symbol
113
        # An Icon and a label below
114
        icon = QLabel()
115
        icon.resize(symbol.pixmap.width(), symbol.pixmap.height())
116
        icon.setPixmap(symbol.pixmap)
117
        layout = QGridLayout()
118
        layout.addWidget(icon, 0, 0, Qt.AlignHCenter)
119
        title = QLabel(symbol.getName())
120
        font = title.font()
121
        font.setPixelSize(10)
122
        title.setFont(font)
123
        layout.addWidget(title, 1, 0, Qt.AlignTop | Qt.AlignHCenter)
124
        self.setLayout(layout)
125
        self.setMaximumSize(96, 96)
126

    
127
    @property
128
    def symbol(self):
129
        return self._symbol
130

    
131
    def keyPressEvent(self, event: QKeyEvent) -> None:
132
        if event.key() == Qt.Key_Delete:
133
            self.parentWidget().remove_library(self)
134
            return
135

    
136
        super(LibraryItem, self).keyPressEvent(event)
137

    
138
    """
139
    Drag and drop management
140
    """
141

    
142
    def enterEvent(self, event):
143
        self.setFrameStyle(QFrame.Panel | QFrame.Sunken)
144
        self.setCursor(Qt.OpenHandCursor)
145
        self.setFocus()
146

    
147
    def leaveEvent(self, event):
148
        self.setFrameStyle(QFrame.NoFrame)
149
        self.setCursor(Qt.ArrowCursor)
150

    
151
    def mousePressEvent(self, mouseEvent):
152
        self.setCursor(Qt.ClosedHandCursor)
153

    
154
    def mouseReleaseEvent(self, mouseEvent):
155
        self.setCursor(Qt.OpenHandCursor)
156

    
157
    def mouseMoveEvent(self, event):
158
        """Drag-n-Drop on left click"""
159
        if event.buttons() != Qt.LeftButton:
160
            return
161

    
162
        mime = QMimeData()
163
        mime.setText(self._symbol.getName())
164

    
165
        drag = QDrag(self)
166
        drag.setMimeData(mime)
167
        originalPoint = self._symbol.getOriginalPoint()
168
        drag.setHotSpot(QPoint(int(float(originalPoint.split(",")[0])), int(float(originalPoint.split(",")[1]))))
169
        drag.setPixmap(self._symbol.pixmap)
170
        drag.exec(Qt.CopyAction)
클립보드 이미지 추가 (최대 크기: 500 MB)