PyQt5 튜토리얼-MenuBar
메뉴 표시 줄은 일반적으로 GUI 의 왼쪽 상단과 제목 표시 줄 아래에 있습니다. 사용자가 메뉴에서 항목을 클릭하면 파일 열기, 파일 저장 또는 응용 프로그램 종료와 같은 작업을 수행 할 수 있습니다.
메뉴 바를 시작하고, 메뉴에 동작을 바인딩하고, 단축키를 추가하고 상태 텍스트를 표시하는 방법을 배웁니다.
PyQt5 메뉴 바 기본 예
대부분의 편집기에서와 같이 ‘파일’메뉴가있는 첫 번째 PyQt5 메뉴 바 예제를 만들 것입니다. 편의를 위해 ‘종료’하위 메뉴 만 포함합니다.
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
class basicMenubar(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initUI()
def initUI(self):
self.setGeometry(200, 200, 200, 200)
exitAction = QAction("&Exit", self)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("Exit application")
exitAction.triggered.connect(qApp.quit)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu("&File")
fileMenu.addAction(exitAction)
self.setWindowTitle("PyQt5 Basic Menubar")
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = basicMenubar()
sys.exit(app.exec_())

menubar = self.menuBar()
QMainWindow 에는 메뉴 바를 만드는 menuBar()메소드가 있습니다.
fileMenu = menubar.addMenu("&File")
fileMenu.addAction(exitAction)
fileMenu 는 이름이 File 인 메뉴 막대에 추가되며 QAction 오브젝트-exitAction 과 연관된 메뉴 항목으로 구성됩니다.
exitAction = QAction("&Exit", self)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("Exit application")
exitAction.triggered.connect(qApp.quit)
애플리케이션을 종료하기 위해 QAction 객체를 생성하고이 객체를 변수 exitAction 에 저장합니다.
이 QAction 객체의 이름은& Exit 이며 단축키 CTRL+Q 와 관련이 있습니다.
exitAction.setStatusTip("Exit application")
사용자가이 메뉴 항목 위로 마우스 포인터를 가져 가면 상태 표시 줄 ‘self.statusBar’에 추가 메시지가 표시됩니다.
exitAction.triggered.connect(qApp.quit)
이 종료 동작이 트리거되는 이벤트를 응용 프로그램의 종료 슬롯에 연결합니다.
PyQt5 메뉴 바 메뉴 항목 아이콘
PyQt5 메뉴 막대에서 메뉴 항목의 아이콘을 설정하는 방법에는 두 가지가 있습니다.
PyQt5 기본 스타일의 표준 픽스맵
기본 스타일의 표준 픽스맵을 사용하여 표준 아이콘으로 메뉴 항목 아이콘을 설정할 수 있습니다.
self.style().standardIcon(QStyle.SP_DialogCancelButton)
위의 코드는 대화 상자 취소의 표준 아이콘을 선택합니다.
![]()
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QStyle
class basicMenubar(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initUI()
def initUI(self):
self.setGeometry(200, 200, 200, 200)
exitAction = QAction(
self.style().standardIcon(QStyle.SP_DialogCancelButton), "&Exit", self
)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("Exit application")
exitAction.triggered.connect(qApp.quit)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu("&File")
fileMenu.addAction(exitAction)
self.setWindowTitle("PyQt5 Basic Menubar")
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = basicMenubar()
sys.exit(app.exec_())
QIcon 과 함께 이미지 파일 사용
QStyle 의 기본 아이콘을 사용하는 위의 방법 외에도, QIcon 클래스를 사용하여 이미지 파일을 아이콘으로 사용할 수도 있습니다.
QIcon("exit.png")
이미지 파일 ’exit.png’를 아이콘으로 설정합니다. exit.png 파일은 파이썬 스크립트 파일과 같은 폴더에 있어야합니다.
![]()
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QStyle
from PyQt5.QtGui import QIcon
class basicMenubar(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initUI()
def initUI(self):
self.setGeometry(200, 200, 200, 200)
exitAction = QAction(QIcon("exit.png"), "&Exit", self)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("Exit application")
exitAction.triggered.connect(qApp.quit)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu("&File")
fileMenu.addAction(exitAction)
self.setWindowTitle("PyQt5 Basic Menubar")
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = basicMenubar()
sys.exit(app.exec_())
PyQt5 메뉴 바 확인 가능한 메뉴 항목
확인 가능한 메뉴 항목을 확인하거나 선택 취소 할 수 있으며 사용자가 클릭 할 때마다 상태가 전환됩니다.
QAction 객체를 만들 때 메뉴 항목을 검사 할 수있게하려면 키워드 인수 checkable 을 True 로 설정해야합니다.
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
class basicMenubar(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(200, 200, 200, 200)
self.label = QLabel("The toggle state is ")
self.label.setAlignment(Qt.AlignCenter)
self.setCentralWidget(self.label)
toggleAction = QAction("&Toggle Label", self, checkable=True)
toggleAction.setStatusTip("Toggle the label")
toggleAction.triggered.connect(self.toggleLabel)
exitAction = QAction(QIcon("exit.png"), "&Exit", self)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("Exit application")
exitAction.triggered.connect(qApp.quit)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu("&File")
fileMenu.addAction(toggleAction)
fileMenu.addAction(exitAction)
self.setWindowTitle("PyQt5 Basic Menubar")
self.show()
def toggleLabel(self, state):
self.label.setText("The toggle state is {}".format(state))
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = basicMenubar()
sys.exit(app.exec_())

toggleAction = QAction("&Toggle Label", self, checkable=True)
QAction객체를 시작할 때 메뉴 항목을 확인할 수있게하려면 checkable속성을 True로 설정해야합니다.
또는 객체가 생성 된 후에 setCheckable()메소드를 사용할 수 있습니다.
self.setCheckable(True)
확인 가능한 항목의 상태는 콜백 함수에 대한 매개 변수입니다. 따라서 함수를 정의 할 때 인수에 나열해야합니다. 처럼
def toggleLabel(self, state):
state 는 부울 타입이며, 선택하면 값은 True이고 선택하지 않으면 False입니다.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook