PyQt5 toolbar
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
exitAct = QAction(QIcon('exit24.png'), 'Exit', self) # 建立一个action对象
exitAct.setShortcut('Ctrl+Q') # 添加快捷键
exitAct.triggered.connect(qApp.quit) # 连接到qApp的quit函数
# Mainwindow的addToolBar方法在mainwindow中创建并返回了一个工具栏,并且我们保存了该工具栏为example的成员变量toolbar
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAct) # 在toolbar中加入action exitAct
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Toolbar')
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
PyQt5 main window
import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication, qApp
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
textEdit = QTextEdit() # 创建一个文本编辑框对象
self.setCentralWidget(textEdit) # 把文本编辑框对象设为mainwindow的中心部件
exitAct = QAction(QIcon('exit24.png'), 'Exit', self) # 创建一个action
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(qApp.quit) # 设置该action被触发后连接到mainwindow的close方法
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAct)
toolbar = self.addToolBar('Exit')
toolbar.addAction(exitAct)
self.setGeometry(300, 300, 350, 250)
self.setWindowTitle('Main window')
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()