파일 열기 대화상자 예제
#ads_1
# -*- coding: utf-8 -*-
import sys
import codecs
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMenuBar, QAction, QTextEdit
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
fileAction = QAction(QIcon("icon.png"), "&Open", self)
fileAction.setShortcut('Ctrl+O')
fileAction.triggered.connect(self.showDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(fileAction)
self.textedit = QTextEdit(self)
self.setCentralWidget(self.textedit)
self.statusBar()
self.setGeometry(300,300,300,300)
self.setWindowTitle('File Window')
self.show()
def showDialog(self, e):
filepath = QFileDialog.getOpenFileName(self, 'Open File', 'd:')
if filepath[0]:
# 일반 open 으로 열었을 경우 아래와 같은 인코딩 에러가 나온다
# UnicodeDecodeError: 'cp949' codec can't decode bytes in position
fp = codecs.open(filepath[0], 'r', 'utf-8')
with fp:
buf = fp.read()
self.textedit.setText(buf)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
#ads_2