23.02.09 Day09

오윤범·2023년 2월 9일
0

GUI(PyQt)

PyQt 설치

  • 위젯 생성 및 Icon 삽입

import sys
from PyQt5.QtWidgets import QApplication,QWidget
from PyQt5.QtGui import QIcon
class MyApp(QWidget):#MyApp class 생성, 부모:Qwidget
    def __init__(self):
        super().__init__()
        self.initUI()#생성자 생성과 동시에 initUI 호출
    def initUI(self):
        self.setWindowTitle('Icon')#Form제목
        self.setWindowIcon(QIcon('.\images\iot.png'))#app Icon 설정
        self.setGeometry(1000,300,500,250)#setGeometry(x,y,너비,높이)
        # self.move(1000,300)#(x,y)위치에 위젯 생성
        # self.resize(500,250)#(너비,높이) 위젯 생성
        self.show()#위젯 출력
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • Quit 버튼 생성

import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QCoreApplication
class MyApp(QWidget):#MyApp class 생성, 부모:Qwidget
    def __init__(self):
        super().__init__()
        self.initUI()#생성자 생성과 동시에 initUI 호출
    def initUI(self):
        btn=QPushButton('Quit',self)
        btn.move(50,50)
        btn.resize(btn.sizeHint())
        btn.clicked.connect(QCoreApplication.instance().quit)#종료
        self.setWindowTitle('Quit Button')#Form제목
        self.setWindowIcon(QIcon('.\images\iot.png'))#app Icon 설정
        self.setGeometry(1000,300,500,250)#setGeometry(x,y,너비,높이)
        # self.move(1000,300)#(x,y)위치에 위젯 생성
        # self.resize(500,250)#(너비,높이) 위젯 생성
        self.show()#위젯 출력
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • 툴팁(ToolTip) 나타내기

import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QToolTip
from PyQt5.QtGui import QIcon,QFont
class MyApp(QWidget):#MyApp class 생성, 부모:Qwidget
    def __init__(self):
        super().__init__()
        self.initUI()#생성자 생성과 동시에 initUI 호출
    def initUI(self):
        QToolTip.setFont(QFont('SansSerif',10))
        self.setToolTip('This is a <b>QWidget</b> widget')#self에 ToolTip찍으니까 widget에
        btn=QPushButton('ToolTipEx',self)#버튼생성
        btn.setToolTip('This is a <b>QPushButton</b> widget')
        btn.move(50,50)#위치
        btn.resize(btn.sizeHint())
        self.setWindowTitle('ToolTip')
        self.setWindowIcon(QIcon('.\images\iot.png'))
        self.setGeometry(1000,300,500,250)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • Statusbar 만들기

import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
class MyApp(QMainWindow):#MyApp class,부모:QMainWindow
    def __init__(self):
        super().__init__()
        self.initUI()#생성자 생성과 동시에 initUI 호출
    def initUI(self):
        self.statusBar().showMessage('Ready')
        self.setWindowTitle('Statusbar')
        self.setGeometry(1000,300,500,250)#setGeometry(x,y,너비,높이)
        self.show()#위젯 출력
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

import sys
from PyQt5.QtWidgets import QApplication,QMainWindow,QAction,qApp
from PyQt5.QtGui import QIcon
class MyApp(QMainWindow):#MyApp class,부모:QMainWindowStatusBar 사용하려면 QMainWindow 필요함
    def __init__(self):
        super().__init__()
        self.initUI()#생성자 생성과 동시에 initUI 호출
	def initUI(self):
        exitAction = QAction(QIcon('.\images\exit.png'),'Exit',self)#아이콘,Exit라벨을 갖는 동작을 만든것
        exitAction.setShortcut('Ctrl+Q')#위 동작의 단축기를 Ctrl+Q로 정의
        exitAction.setStatusTip('Exit application')#라벨에 마우스 올렸을 때 상태바에 Exit application 출력
        exitAction.triggered.connect(qApp.quit)#내가만든 exitAction동작 선택 시 quit()메서드에 연결되면서 종료
        self.statusBar()#상태바(위젯 하단)
        menubar=self.menuBar()#메뉴바생성
        menubar.setNativeMenuBar(False)
        filemenu=menubar.addMenu('&File')#File메뉴 만드는데 &File로 만들면 해당 메뉴 단축키가 Alt+F가 됨.
        filemenu.addAction(exitAction)#File메뉴에 exitAction 동작 추가
        self.setWindowTitle('Menubar')
        self.setGeometry(1000,300,500,250)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

-->filemenu=menubar.addMenu('&File')와 같이 'File'이 아닌 '&File'로 선언하여 alt+f 로 단축키 사용 가능
-->setShortcut 함수를 통해 단축키 정의 가능

  • Toolbar 만들기

import sys
from PyQt5.QtWidgets import QApplication,QMainWindow,QAction,qApp
from PyQt5.QtGui import QIcon
class MyApp(QMainWindow):#MyApp class,부모:QMainWindow
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        exitAction = QAction(QIcon('.\images\exit.png'),'Exit',self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)#종료하는 동작 추가
        self.statusBar()
        self.toolbar = self.addToolBar('Exit') #마우스 올리면 Exit나옴
        self.toolbar.addAction(exitAction)#위에 설정한 exitAction을 toolbar에 뿌려줌
        self.setWindowTitle('Toolbar')
        self.setGeometry(1000,300,500,250)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • 날짜와 시간 출력하기

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QDate,QTime,QDateTime
class MyApp(QMainWindow):#MyApp class,부모:QMainWindow / StatusBar 사용하려면 QMainWindow 필요함
    def __init__(self):
        super().__init__()
        self.initUI()#생성자 생성과 동시에 initUI 호출
    def initUI(self):
        exitAction = QAction(QIcon('.\images\exit.png'),'Exit',self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)
        self.statusBar()
        testicon=QAction(QIcon('.\images\iot.png'),'iot',self)
        self.toolbar = self.addToolBar('Tooolbar') #마우스 올리면 Exit나옴
        self.toolbar.addAction(exitAction)
        self.toolbar.addAction(testicon)
        #상태바에 날짜 출력
        now=QDate.currentDate()#날짜
        time=QTime.currentTime()#시간
        datetime=QDateTime.currentDateTime()
        self.statusBar().showMessage(now.toString('yyyy년 MM월 dd일')+' '+time.toString())
        #self.statusBar().showMessage(datetime.toString())
        menubar=self.menuBar()
        menubar.setNativeMenuBar(False)
        filemenu=menubar.addMenu('&File')
        filemenu.addAction(exitAction)
        self.setWindowTitle('Menubar+Toolbar')
        #self.setGeometry(1000,300,500,250)
        self.setcenter()#중심정렬
        self.resize(400,300)
        self.show()
    # 화면 중심 셋팅
    def setcenter(self):
        qr=self.frameGeometry()
        cp=QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
if __name__=='__main__':
    app=QApplication(sys.argv)#Application 객체 생성
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------


--> (now,time) 사용한 경우 / dateTime 사용한 경우

  • Style 꾸미기

import sys
from PyQt5.QtWidgets import *
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        #스타일
        label1=QLabel('Red')
        label2=QLabel('Green')
        label3=QLabel('Blue')
        label1.setStyleSheet("color:red;"#글자색
                            "border-style:solid;"#경계선:실선
                            "border-width:4px;"#경계선두께
                            "border-color:#FA8072;"#경계선색
                            "border-radius:3px")#경계선모서리
        label2.setStyleSheet("color:green;"
                            "background-color:#7FFFD4")#배경색
        label3.setStyleSheet("color:blue;"
                            "border-style:dashed;"
                            "border-width:4px;"
                            "border-color:#1E90FF")
        vbox=QVBoxLayout()#VBox : 가로로 출력 / HBox : 세로로 출력
        vbox.addWidget(label1)
        vbox.addWidget(label2)
        vbox.addWidget(label3)
        self.setLayout(vbox)
        self.setWindowTitle('stylesheet')
        self.setGeometry(1000,300,300,300)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • 레이아웃(절대적 배치)

#레이아웃 절대적 배치
import sys
from PyQt5.QtWidgets import *
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        label1=QLabel('Label1',self)
        label1.move(20,20)
        label2=QLabel('Label2',self)
        label2.move(20,60)
        button1=QPushButton('Button1',self)
        button1.move(80,13)
        button2=QPushButton('Button2',self)
        button2.move(80,53)
        self.setWindowTitle('Absolute Positioning')
        self.setGeometry(300,300,300,300)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • 레이아웃(상대적 배치)

#레이아웃 절대적 배치
import sys
from PyQt5.QtWidgets import *
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        okButton=QPushButton('OK')
        cancleButton=QPushButton('Cancel')
        hbox=QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancleButton)
        hbox.addStretch(1)
        vbox=QVBoxLayout()
        vbox.addStretch(3)
        vbox.addLayout(hbox)
        vbox.addStretch(1)#addStretch로 아래 위 공간 3:1로 유지
        self.setLayout(vbox)
        self.setWindowTitle('박스 배치')
        self.setGeometry(300,300,300,300)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------


---> 이와 같은 의미

  • 레이아웃 배치(Grid)

import sys
from PyQt5.QtWidgets import *
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):        
        grid=QGridLayout()
        self.setLayout(grid)
        grid.addWidget(QLabel('Title'),0,0) #row,col=0,0
        grid.addWidget(QLabel('Title'),1,0) #1행 0열
        grid.addWidget(QLabel('Title'),2,0) #2행 0열 
        grid.addWidget(QLineEdit(),0,1) #0행 1열
        grid.addWidget(QLineEdit(),1,1) #1행 1열
        grid.addWidget(QTextEdit(),2,1) #2행 1열
        okButton=QPushButton('OK') #버튼도 추가해보자
        cancleButton=QPushButton('Cancel')
        grid.addWidget(okButton,3,1) #3행 1열
        grid.addWidget(cancleButton,4,1) #4행 1열      
        self.setWindowTitle('그리드 배치')
        self.setGeometry(300,300,300,300)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • QPushButton

#레이아웃 절대적 배치
import sys
from PyQt5.QtWidgets import *
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        button1=QPushButton('Button&1',self)#&Button으로 선언하여 Alt+B로 버튼 활성화 가능(단축키st)
        button1.setCheckable(True)#선택(체크)상태
        button1.toggle()#toggle 호출 해야 시작과 동시에 버튼선택된 상태로 나옴
        button2=QPushButton('Button&2',self)#버튼선택 단축키 &2
        button2.setCheckable(True)
        button2.toggle()
        button3=QPushButton('Button3',self)#버튼선택 단축키 &2
        button3.setEnabled(False)#선택못함
        vbox=QVBoxLayout()
        vbox.addWidget(button1)
        vbox.addWidget(button2)
        vbox.addWidget(button3)
        self.setLayout(vbox)
        self.setWindowTitle('버튼')
        self.setGeometry(300,300,300,300)
        self.show()
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------

  • checkButton/radioButton

#레이아웃 절대적 배치
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        cb1=QCheckBox('CheckBox1',self)#다중선택 가능
        cb1.move(20,20)
        cb1.toggle()
        #signal
        cb1.stateChanged.connect(self.changeTitle)
        cb2=QCheckBox('CheckBox2',self)
        cb2.move(20,60)
        cb2.stateChanged.connect(self.changeCheck)
        rb1=QRadioButton('First Button',self)
        rb1.move(20,120)
        rb1.setChecked(True)
        rb2=QRadioButton('Second Button',self)#다중선택 불가
        rb2.move(20,160)
        self.setWindowTitle('Check,Radio Button')
        self.setGeometry(1000,300,300,300)
        self.show()
    def changeCheck(self,state):
        if state==Qt.CheckState.Checked:
            self.setWindowTitle('CbeckBox2 체크됨')
        else:
            self.setWindowTitle('CbeckBox2 체크됨')
    def changeTitle(self,state):#상태 변경될때
        if state == Qt.CheckState.Checked:
            self.setWindowTitle('CheckBox1 체크됨')
        else:
            self.setWindowTitle('CheckBox1 체크해제')
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=MyApp()
    sys.exit(app.exec_())
---------------------------출력-------------------------
---------------------------출력-------------------------


--> CheckBox 1,2 동시 선택 시 출력문 if문으로 수정해야 하지만 너무 기초적이고 원시적이라 안함

0개의 댓글