本实例环境PyQt5+Python3.5+ubuntu16
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, qApp, QLineEdit, QHBoxLayout, QWidget
from PyQt5.QtGui import QIcon
__windowtitle__ = '菜单栏' #设置一个全局私有变量,只能在本.py文件中访问的变量
# 菜单栏演示
class menubarDemo(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.statusBar() #创建一个空的状态栏
menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('File')
setMenu = menubar.addMenu('setting')
toolMenu = menubar.addMenu('Tool')
self.lineEdit = QLineEdit()
self.lineEdit.setText('这是字体')
layout = QHBoxLayout()
layout.addWidget(self.lineEdit)
widGet = QWidget()
widGet.setLayout(layout)
self.setCentralWidget(widGet)
#Tool菜单功能
toolAction = QAction(QIcon('exit.png'), '设置字体颜色', self) #QIcon是设置图标,随便找一个.png图片放项目目录下并命名为exit.png
toolAction.setShortcut('Ctrl+F') #设置快捷键
toolAction.setStatusTip('改变字体颜色') #当鼠标放到改Action上时显示的提示信息(左下角)
toolAction.triggered.connect(self.setFont) #点击toolAction后要触发的操作,这里链接到setFont方法
#setting菜单功能
setAction = QAction(QIcon('exit.png'), '窗口设置', self)
setAction.setShortcut('Ctrl+W')
setAction.setStatusTip('设置窗口大小')
setAction.triggered.connect(self.windowresize)
#exit菜单功能
exitAction = QAction(QIcon('exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit Application')
exitAction.triggered.connect(qApp.quit)
#空操作
noneAction = QAction(QIcon('exit.png'), '空操作', self)
noneAction.setStatusTip('不做任何操作')
noneAction.setShortcut('Ctrl+n')
#将这个Action添加到fileMenu上
fileMenu.addAction(exitAction)
setMenu.addAction(setAction)
toolMenu.addAction(toolAction)
fileMenu.addAction(noneAction)
self.setWindowTitle(__windowtitle__)
self.setGeometry(300, 300, 450, 450)
self.show()
def windowresize(self):
self.resize(300, 300)
def setFont(self):
self.lineEdit.setStyleSheet("color:red")
if __name__ == '__main__':
app = QApplication(sys.argv)
example = menubarDemo()
sys.exit(app.exec_())
效果: