Side Project#/PEDU

Develop PEDU with pyqt4 - 3

ch4rli3kop 2018. 6. 27. 01:47
반응형

이번에도 역시 저번처럼 메뉴 바와 툴 바를 추가할 예정입니다. 다만 이번에 추가할 동작은 계산기로, 단순한 함수보다 어떤 클래스를 이용하여 구현된 함수를 통하여 계산기 기능을 추가하도록 하겠습니다.


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
from PyQt4.QtGui import *
from PyQt4.QtCore import*
import sys
 
 
class MyWindow(QMainWindow):
   def __init__(self):
      QMainWindow.__init__(self)
 
      ### 윈도우 특성 설정 ###
      self.setWindowTitle('PEDU')
      self.setGeometry(400,200,1500,600)
      #self.setWindowIcon(QIcon(''))
      self.statusBar().showMessage('ready')
      self.creat_menubar_child()
      self.creat_menubar()
      self.show()
 
 
   def creat_menubar_child(self):
      ### 메뉴바 설정 ###
      #load file
      self.fileAction1 = QAction("load file",self)
      self.fileAction1.setShortcut("Ctrl+O")
      self.fileAction1.setStatusTip("Load the file in local place")# 밑에서 상태를 알려줌
      self.fileAction1.triggered.connect(self.open_file)
 
      #exit 
      self.fileAction2 = QAction("Exit",self)
      self.fileAction2.setShortcut("Ctrl+C")
      self.fileAction2.setStatusTip("Exit the App")
      self.fileAction2.triggered.connect(self.close_window)
 
      #change font
      self.fileAction3 = QAction("Change Font",self)
      self.fileAction3.setShortcut("Ctrl+T")
      self.fileAction3.setStatusTip("Change the string font in application")
      self.fileAction3.triggered.connect(self.change_font)
 
      #calculater
      self.fileAction4 = QAction("Calculater", self)
      self.fileAction4.setShortcut("Ctrl+E")
      self.fileAction4.setStatusTip("Pop up the calculater")
      self.fileAction4.triggered.connect(self.popCalc)
 
 
   def creat_menubar(self):
      ### MenuBar ###
      mainMenu = self.menuBar()
      
      #File      
      fileMenu1 = mainMenu.addMenu('File')
      fileMenu1.addAction(self.fileAction1)
      fileMenu1.addAction(self.fileAction2)
 
      #Option
      fileMenu2 = mainMenu.addMenu('Options')
      fileMenu2.addAction(self.fileAction3)
 
      #Tool
      fileMenu3 = mainMenu.addMenu('Tools')
      fileMenu3.addAction(self.fileAction4)
 
      ### toolbar 설정 ###
      #open_file
      # openIcon = QIcon()
      # openIcon.addFile('openFileImage2.png', QSize(16,16))
      # openAction = QAction(toolIcon, 'open_file', self)
      openAction = QAction(QIcon('file_open.png'), 'Open', self)
      openAction.triggered.connect(self.open_file)
 
      #exit_file
      exitAction = QAction(QIcon('exit.png'), 'Exit', self)
      exitAction.triggered.connect(self.close_window)
 
      #change_font
      setFontAction = QAction(QIcon('option.png'), 'Setting', self)
      setFontAction.triggered.connect(self.change_font)
 
      #pop_calculater
      calcAction = QAction(QIcon('calculater.png'), 'Calculater', self)
      calcAction.triggered.connect(self.popCalc)
 
 
      #open_file2
      self.openToolBar = self.addToolBar("Open")
      self.openToolBar.addAction(openAction)
 
      #exit_file2
      self.exitToolBar = self.addToolBar("Exit")
      self.exitToolBar.addAction(exitAction) 
 
      #change_font2
      self.setToolBar = self.addToolBar("Setting")
      self.setToolBar.addAction(setFontAction)
 
      #pop_calculater2
      self.calcToolBar = self.addToolBar("Calculater")
      self.calcToolBar.addAction(calcAction)
 
 
   def open_file(self):
      global filename
      filename = QFileDialog.getOpenFileName(self, "Select file")
      global Pfile
      Pfile = pefile.PE(filename)
 
 
   def close_window(self):
      result = QMessageBox.question(self, 'Message',"Are you sure you leave?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
 
      if result == QMessageBox.Yes:
         sys.exit()
      else:
         pass
      
 
   def change_font(self):
      font, valid = QFontDialog.getFont()
      if valid:
         self.styleChoice.setFont(font)
 
   def popCalc(self):
      form = calculater()
      form.show()
 
 
class calculater(QDialog):
    # 창 초기화
    def __init__(self, parent=None):
        super().__init__(parent)
        self.old = ''
        self.new = '0'
        self.operator = ''
 
        layout = QGridLayout()
        self.label = QLabel()
        self.label.setText('<p align="right"><font size=30><b>' + self.new + '</b></font></p>')
        layout.addWidget(self.label, 0014)  # 0, 0 위치에서 행으로 1칸, 열로 4칸의 크기를 갖도록 함.
        # 버튼 생성과 위치 지정
        for index, value in enumerate(['7''8''9''/''4''5''6''*''1''2''3''-''0''.''=''+']):
            button = QPushButton(value)
            layout.addWidget(button, index // 4 + 1, index % 4)
 
        self.setLayout(layout)
        self.setWindowTitle('계산기')
 
        for index, value in enumerate(['7''8''9''/''4''5''6''*''1''2''3''-''0''.''=''+']):
            button = QPushButton(value)
            layout.addWidget(button, index // 4 + 1, index % 4)
            if value in ['/''*''-''+''=']:
                self.connect(button, SIGNAL('clicked()'), lambda who=value: self.calculate(who))
            else:
                self.connect(button, SIGNAL('clicked()'), lambda who=value: self.num_input(who))
 
    # 레이블 업데이트
    def updateResult(self, text):
        self.label.setText('<p align="right"><font size=30><b>' + text + '</b></font></p>')  # 항상 현재 값을 표시.
 
    # 계산 메소드
    def calculate(self, who):
        try:
            # = 버튼 처리
            if who == '=':
                # 이전 값과 연산자가 있을 때만 계산
                if self.old != '' and self.operator != '':
                    self.new = str(eval(self.old + self.operator + self.new))
                    self.old = ''
                    self.operator = who
            # 연산자 처리
            else:
                # 이전 값이 있을 경우 이전 값과 현재 값을 계산 후 연산자 대입.
                if self.old != '':
                    self.new = str(eval(self.old + self.operator + self.new))
                    self.old = ''
                self.operator = who
        except:
            self.new = '오류!'
            self.old = ''
            self.operator = ''
        self.updateResult(self.new)
 
    # 숫자와 소수점 처리
    def num_input(self, who):
        # 오류가 발생한 경우 초기화
        if self.new == '오류!':
            self.new = '0'
            self.old = ''
            self.operator = ''
        # 계산 후 숫자를 누르면 초기화
        if self.operator == '=':
            self.new = '0'
            self.operator = ''
        # 이전 값은 없고, 연산자가 있을 경우 이전 값에 현재 값을 대입하고, 현재 값 새로 입력.
        if self.old == '' and self.operator != '':
            self.old = self.new
            if who == '.':
                self.new = '0.'
            else:
                self.new = who
        # 일반적인 경우
        else:
            # 소수점일 경우 현재 값에 소수점이 없을 때만 소수점 입력.
            if who == '.':
                if '.' not in self.new:
                    self.new = self.new + who
            else:
                # 현재 값이 0일 경우 숫자를 누르면 그 숫자가 바로 입력.
                if self.new == '0':
                    self.new = who
                else:
                    self.new = self.new + who
        self.updateResult(self.new)
 
 
 
if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = MyWindow()
   sys.exit(app.exec_())
cs



실행 화면은 다음과 같습니다.

단순히 계산기를 과정이었습니다만, 조금 복잡한 클래스를 사용하기 때문에 추가적으로 집필하였습니다. 이 과정을 통해서 한가지 기능을 추가할 때 어떤 어떤 것을 추가해야 할 지 파악하는데 도움이 될 것 같습니다.


반응형

'Side Project# > PEDU' 카테고리의 다른 글

Develop PEDU with pyqt4 - 4  (0) 2018.06.27
Develop PEDU with pyqt4 - 2  (0) 2018.06.27
Develop PEDU with pyqt4 - 1  (0) 2018.06.27
Develop PEDU with pyqt4  (0) 2018.06.26