經(jīng)過之前的學(xué)習,我們掌握了菜單欄、工具欄以及狀態(tài)欄的添加方法,現(xiàn)在不妨試試把它們整合在一起,然后再加上一個中心窗口,一個完整的 App 初見端倪。本文由 Cescfangs 譯自ZetCode pyqt5系列教程 并作適當修改。
先上源代碼:
import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QApplication, qApp, QAction
from PyQt5.QtGui import QIcon
class exp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
text = QTextEdit()
self.setCentralWidget(text)
exitAct = QAction(QIcon('heart256.ico'), 'Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Press and quit')
exitAct.triggered.connect(qApp.quit)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(exitAct)
self.statusBar()
tbar = self.addToolBar('Exit')
tbar.addAction(exitAct)
self.setGeometry(400, 200, 600, 400)
self.setWindowTitle('all together')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = exp()
sys.exit(app.exec_())
主界面
這個界面中的許多元素其實我們在之前的學(xué)習筆記中已經(jīng)實現(xiàn)過了,通過上面的代碼,我們成功地把桌面 GUI 界面常見的一些功能集合在了一起,有菜單欄、工具欄和狀態(tài)欄。
text = QTextEdit()
self.setCentralWidget(text)
以上代碼創(chuàng)建了一個文字編輯的窗口 QTextEdit()
,可以用來輸入文字,再用setCentralWidget()
把這個編輯窗口放在QMainWindow
的中心,QTextEdit()
將會占據(jù)界面的所有剩余空間。
效果演示
是不是注意到動圖里沒有 “File”?因為 Mac 的菜單欄統(tǒng)一集成在最上面,通過 PyQt 設(shè)置的菜單欄并不會集成在 Mac 的頂部菜單欄上所以看上去和 Windows 不一樣。