I want to add menu bar to my window (which is a QWidget instance), I searched on the Google and found that most articles are recommending to use QMainWindow instead of QWidget. Using QMainWindow is a good choice, but in my program the main window is based on QWidget and the code base is huge, so adding menu bar to QWidget is a better choice here.
First we need create a window (QWidget) and set its layout (we use QVBoxLayout here)
|
window = QWidget() vbox = QVBoxLayout() window.setLayout(vbox) |
Then create a menu bar and add it to the VBox layout.
|
menu_bar = QMenuBar() vbox.addWidget(menu_bar) |
Now you will see a blank menu bar in your window
Next we need add some menus to our menu bar
|
file_menu = menu_bar.addMenu('File') edit_menu = menu_bar.addMenu('Edit') |
addMenu function will take the parameter as menu name and return the menu as return value. We need keep the menu instances because we need add actions (menu items) to them.
|
exit_action = QAction('Exit', window) exit_action.triggered.connect(exit) file_menu.addAction(exit_action) |
In above code we create a QAction (menu item) with title "Exit", and connect its "triggered" signal to exit function (sys.exit), it means when this menu item is clicked, the exit function will be called. Finally add this menu item to the "File" menu.
We can also connect QAction's triggered signal to custom defined function
|
def redoClicked(): msg_box = QMessageBox() msg_box.setText('Redo will be performed') msg_box.exec_() redo_action = QAction('Redo', window) redo_action.triggered.connect(redoClicked) edit_menu.addAction(redo_action) |
Here we add a "Redo" menu item under "Edit" menu. When user clicks "Redo", a message box will be popped up saying "Redo will be performed"
Following is the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
from PySide.QtCore import * from PySide.QtGui import * import sys def redoClicked(): msg_box = QMessageBox() msg_box.setText('Redo will be performed') msg_box.exec_() app = QApplication(sys.argv) window = QWidget() vbox = QVBoxLayout() menu_bar = QMenuBar() file_menu = menu_bar.addMenu('File') edit_menu = menu_bar.addMenu('Edit') exit_action = QAction('Exit', window) exit_action.triggered.connect(exit) file_menu.addAction(exit_action) redo_action = QAction('Redo', window) redo_action.triggered.connect(redoClicked) edit_menu.addAction(redo_action) window.setLayout(vbox) vbox.addWidget(menu_bar) window.show() app.exec_() |