본문 바로가기

프로그래밍/PyQt5 GUI

8. 툴바 만들기

아이콘을 이용하여 메뉴바 아래에 자주 사용하는 명령을 모아 놓은 것이 툴바입니다. (QToolBar 공식 문서) 참고

폴더 안에 toolbar의 각 기능에 해당하는 아이콘을 저장합니다.

save.png, edit.png, print.png, exit.png

8-1 예제

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, qApp, QToolBar
from PyQt5.QtGui import QIcon

class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        self.statusBar()

        toolbar = QToolBar('Exit', self)
        toolbar.addAction(exitAction)
        self.addToolBar(toolbar)

        #self.toolbar = self.addToolBar('Exit')
        #self.toolbar.addAction(exitAction)

        self.setWindowTitle('Toolbar')
        self.setGeometry(300, 300, 300, 200)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

8-2 설명

exitAction = QAction(QIcon('exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
  • toolbar에서 동작할 QAction 객체를 생성하고 QIcon을 통하여 아이콘을 추가합니다.
  • QAction 클래스의 setShortcut() 메서드를 통하여 단축키 (Ctrl+Q)를 추가합니다.
  • QAction 클래스의 setStatusTip() 메서드를 통하여 toolbar에 마우스를 올리면 statusbar에 출력될 상태바 메시지를 추가합니다.
  • QAction에 실행될 동작으로 triggered 시그널을 QApplication 위젯의 quit 메서드 슬롯에 연결하여 어플리케이션을 종료합니다.
toolbar = QToolBar('Exit', self)
toolbar.addAction(exitAction)
self.addToolBar(toolbar)
  • QToolBar를 이용하여 toolbar 객체를 생성하고 toolbar에서 동작을 addAction() 을 이요해서 툴바에 exitAction 동작을 추가합니다.
  • QMainWindow 클래스에 addToolBar를 통하여 툴바를 추가합니다.

8-3 결과

'프로그래밍 > PyQt5 GUI' 카테고리의 다른 글

10. 날짜와 시간 표시하기  (0) 2021.07.22
9. 창을 화면의 가운데로  (0) 2021.07.22
7. 메뉴바 만들기  (0) 2021.07.22
6. 상태바 만들기  (0) 2021.07.22
5. 툴팁 보이기  (0) 2021.07.21