PyQt5入門(二)——選單、工具、狀態列
阿新 • • 發佈:2018-12-16
此總結主要參考下面這篇文章:PyQt5選單和工具欄
狀態列、選單欄和工具欄是QWidget類沒有的,文中出現的self預設繼承了QMainWindow的類
1. 狀態列
from PyQt5.QtWidgets import QMainWindow # 這裡只匯入與內容直接相關的庫
self.statusBar().showMessage('Ready')
# 預設前面已經繼承了QMainWindow的類
# 先呼叫statusBar()建立一個狀態列,後續呼叫返回的狀態列物件,在狀態列上顯示一條訊息
2. 選單欄
from PyQt5.QtWidgets import QAction # 事件,與選單欄非直接相關,但是讓每個選單欄有意義必須有這個
from PyQt5.QtWidgets import qApp # 與選單欄無關,只是這裡的示例用到了它
from PyQt5.QtGui import QIcon # 非必須只是一個點綴
self.statusBar()
exitAction = QAction(QIcon('web.png'),'&Exit',self) #這裡的‘&’應該是在右側的字母下新增下劃線,但是我這裡執行之後和不加沒區別
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application' )
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
3.工具欄
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
# 下面這麼寫也是OK的,但是寫成類似上一個示例是不行的
# toolbar = self.addToolBar('Exit')
# toolbar.addAction(exitAction)
綜合上述功能得到如下示例:
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, qApp
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 建立事件
exitAction = QAction('E&xit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
# 建立一個選單欄
menubar = self.menuBar()
# 新增選單
fileMenu = menubar.addMenu('File')
# 新增事件
fileMenu.addAction(exitAction)
# 新增一個工具欄
toolbar = self.addToolBar('Exit')
toolbar.addAction(exitAction)
self.statusBar().showMessage('Ready')
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Menubar')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())