標籤:功能表列 span exec shortcut title app show sage post
例子:狀態列、功能表列和工具列
import sysfrom PyQt4 import QtGuiclass Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): textEdit = QtGui.QTextEdit() self.setCentralWidget(textEdit) exitAction = QtGui.QAction(QtGui.QIcon(), ‘Exit‘, self) exitAction.setShortcut(‘Ctrl+Q‘) exitAction.setStatusTip(‘Exit application‘) exitAction.triggered.connect(self.close) bar1=self.statusBar()
bar1.showMessage(‘Ready‘) menubar = self.menuBar() fileMenu = menubar.addMenu(‘&File‘) fileMenu.addAction(exitAction) toolbar = self.addToolBar(‘Exit‘) toolbar.addAction(exitAction) self.setGeometry(300, 300, 350, 250) self.setWindowTitle(‘Main window‘) self.show()def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_())if __name__ == ‘__main__‘: main()
運行效果如下:
下面解釋上面的代碼:
class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() self.initUI()
注意Example類繼承於QtGui.QMainWindow
QtGui.QMainWindow類提供了建立應用主視窗的方法,這使得用狀態列(statusbar)、功能表列(menubar)、工具列(toolbar)建立一個傳統的應用程式框架成為可能。
textEdit = QtGui.QTextEdit()self.setCentralWidget(textEdit)
這裡我們建立了一個文本編輯框(text edit)組件。我們把它設定成QtGui.QMainWindow的中央組件,中央組件佔據了各種欄之外所有的剩餘空間
exitAction = QtGui.QAction(QtGui.QIcon(), ‘Exit‘, self) exitAction.setShortcut(‘Ctrl+Q‘) exitAction.setStatusTip(‘Exit application‘) exitAction.triggered.connect(self.close) menubar = self.menuBar() fileMenu = menubar.addMenu(‘&File‘) fileMenu.addAction(exitAction)
在上面這個樣本中,我們建立了只由一個菜單組成的功能表列。這個菜單也僅僅擁有一個選項【這裡原文是action,為了方便理解,我們下面將這個action有時翻譯成選項。】:結束應用。而且我們給這個選項添加了一個快速鍵:Ctrl+Q。
Qt.Gui.QAction是這個行為的一個抽象。在上面這三行中,我們建立了有著自己表徵圖和名字一個選項,而且,我們給這個行為定義了一個快速鍵。第三行建立了一個status tip,它的作用是滑鼠放在這個選項上時,可以在狀態列中顯示出狀態“Exit application”。
當我們選擇了這個選項時,一個觸發訊號(triggered signal)被發出了。這個訊號和QtGui.QApplication組件的quit()方法相聯絡(connect),所以訊號發出後,程式終止。
menuBar()方法建立了一個功能表列。這裡我們在功能表列的基礎上建立了一個file菜單,並在裡面添加了exit選項
bar1=self.statusBar() bar1.showMessage(‘Ready‘)
為了得到一個狀態列,我們調用了QtGui.QMainWindow類中的statusBar()方法【注意Example是繼承QMainWindow的】。函數調用建立了一個狀態列,接下來的showMessage()函數調用返回了一個狀態列對象,showMessage()裡面的參數是顯示在狀態列中的。
toolbar = self.addToolBar(‘Exit‘) toolbar.addAction(exitAction)
我們建立了一個工具列並且給裡面加入了一個選項, 就是菜單選項exitAction
Python pyQt4學習筆記2