对于一个较大的软件,在它的菜单栏里可以找到所有的功能,但是对于大多数用户来说,经常使用的往往就是那几个功能,工具栏的存在就是方便用户找到频繁使用的功能。
本文由 Cescfangs 译自ZetCode pyqt5系列教程 并作适当修改。
上源代码先:
import sys
from PyQt5.QtWidgets import QApplication, qApp, QMainWindow, QAction
from PyQt5.QtGui import QIcon
class Toolbar(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
exitAct = QAction(QIcon('heart256.ico'), '&Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.triggered.connect(qApp.quit)
exitAct.setStatusTip('Be careful')
self.toolbar = self.addToolBar('Exitoo')
self.toolbar.addAction(exitAct)
self.statusBar()
self.setGeometry(300, 300, 400, 240)
self.setWindowTitle('Toolbar')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Toolbar()
sys.exit(app.exec_())

上面的代码实现了一个简单的工具栏按钮,他的功能和上一篇学习笔记(PyQt5学习笔记(六):创建菜单栏)是一样的,都是起到关闭程序的作用。
exitAct = QAction(QIcon('heart256.ico'), '&Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.triggered.connect(qApp.quit)
与之前的菜单栏一样,我们创建了这个退出的动作,鼠标悬停时提示这个动作的功能(Exit)。
self.toolbar = self.addToolBar('Exitoo')
self.toolbar.addAction(exitAct)
self.statusBar()
不同的是,这次我们把这个动作添加到工具栏里,同时当鼠标悬浮到工具栏的按钮时,底部的状态栏会提示 'Be careful'。

网友评论