Adding menus

Once the menu bar is set, menu list can be added to it. The PySide.QtGui.QMenu class provides menu widget for use in menu bars, context menus, and other popup menus. A menu widget is a selection menu. It can be either a pull-down menu in a menu bar or can be a context menu. Pull-down menus are shown by the menu bar when the user clicks on the respective item or presses the specified shortcut key. Context menus are invoked by some special keyboard key or by right-clicking on it.

In the menu bar, we add menus with the function QMenuBar.addMenu(menu). For the example application, we add three menus namely, File, Edit, and About. Inside each of these menus, we create two actions each that when triggered by click or a keyboard shortcut key combination connects to a specified slot. As defined, a menu consists of a list of action items. The PySide.QtGui.QAction class provides an abstract user interface action that can be inserted into widgets. Actions are common for a combination of menu items, tool bars, and keyboard shortcuts. So we create an action and attach it with different components, which are expected to perform the same functionality. Usually, when an action is created, it should be added to the relevant menu and toolbar, then connected to the slot which will perform the action. Actions are added to the menus with the QMenu.addAction(), QMenu.addActions(), and QMenu.insertAction() functions. An action is rendered vertically under the menu, and can have a text label, an optional icon drawn on the left, and a shortcut key sequence.

The following example demonstrates the creation of menu bar in the main window application. This program is a shortened version of what we will be developing as a fully working "A Simple Text Editor" application at the end of this chapter.

# Import required modules
import sys
from PySide.QtGui import QApplication, QMainWindow, QStatusBar, QTextEdit, 
    QAction, QIcon, QKeySequence

class MainWindow(QMainWindow):
  """ Our Main Window class
  """

  def __init__(self):
    """ Constructor Function
    """
    QMainWindow.__init__(self)
    self.setWindowTitle("A Simple Text Editor")
    self.setWindowIcon(QIcon('appicon.png'))
    self.setGeometry(300, 250, 400, 300)

  def SetupComponents(self):
    """ Function to setup status bar, central widget, menu bar
    """
    self.myStatusBar = QStatusBar()
    self.setStatusBar(self.myStatusBar)
    self.myStatusBar.showMessage('Ready', 10000)
    self.textEdit = QTextEdit()
    self.setCentralWidget(self.textEdit)
    self.CreateActions()
    self.CreateMenus()
    self.fileMenu.addAction(self.newAction)
    self.fileMenu.addSeparator()
    self.fileMenu.addAction(self.exitAction)
    self.editMenu.addAction(self.copyAction)
    self.fileMenu.addSeparator()
    self.editMenu.addAction(self.pasteAction)
    self.helpMenu.addAction(self.aboutAction)


  # Slots called when the menu actions are triggered
  def newFile(self):
    self.textEdit.setText('')

  def exitFile(self):
    self.close()
  
  def aboutHelp(self):
    QMessageBox.about(self, "About Simple Text Editor",
        "This example demonstrates the use "
        "of Menu Bar")

  def CreateActions(self):
    """ Function to create actions for menus
    """
    self.newAction = QAction( QIcon('new.png'), '&New',
                self, shortcut=QKeySequence.New,
                statusTip="Create a New File",
                triggered=self.newFile)
    self.exitAction = QAction( QIcon('exit.png'), 'E&xit',
                self, shortcut="Ctrl+Q",
                statusTip="Exit the Application",
                triggered=self.exitFile)
    self.copyAction = QAction( QIcon('copy.png'), 'C&opy',
                self, shortcut="Ctrl+C",
                statusTip="Copy",
                triggered=self.textEdit.copy)
    self.pasteAction = QAction( QIcon('paste.png'), '&Paste',
                self, shortcut="Ctrl+V",
                statusTip="Paste",
                triggered=self.textEdit.paste)
    self.aboutAction = QAction( QIcon('about.png'), 'A&bout',
                self, statusTip="Displays info about text editor",
                triggered=self.aboutHelp)

  # Actual menu bar item creation
  def CreateMenus(self):
    """ Function to create actual menu bar
    """
    self.fileMenu = self.menuBar().addMenu("&File")
    self.editMenu = self.menuBar().addMenu("&Edit")
    self.helpMenu = self.menuBar().addMenu("&Help")
    
if __name__ == '__main__':
  # Exception Handling
  try:
    #QApplication.setStyle('plastique')
    myApp = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.SetupComponents()
    mainWindow.show()
    myApp.exec_()
    sys.exit(0)
  except NameError:
    print("Name Error:", sys.exc_info()[1])
  except SystemExit:
    print("Closing Window...")
  except Exception:
    print(sys.exc_info()[1])

In the preceding example, the actions are created in the CreateActions() function. Each of the menu items are created as separate actions.

Note

self.newAction = QAction( QIcon('new.png'), '&New',
self, shortcut=QKeySequence.New,
statusTip="Create a New File",
triggered=self.newFile)

The New item under File menu has the action instantiated as preceding code snippet. The first parameter is the Icon to be displayed on to the left of the menu item. The next parameter is the name to be displayed. The & represents that the letter followed by it should be underlined, and can be accessed by pressing the Alt + <letter> combination as in many other window applications. The third parameter implies the parent which is the main window here. The fourth and fifth keyword parameters represent the shortcut key combination for easy access of the menu item and status tip to be displayed on highlighting the menu item respectively. The shortcut key can be either a predefined combination by the PySide.QtGui.QKeySequence class or a valid combination as given by the user. The PySide.QtGui.QKeySequence class encapsulates a key sequence as used by shortcuts. It defines a combination of keys that can be used by different operating system platforms. The last parameter defines the slot to be called when the menu item is triggered, which can be a logical group of code executing the desired functionality. We define the other actions similar to this.

Once the actions are created, we add these actions to the menu items. The top level menu bar is created in the CreateMenus() function and the actions of the menu items are added as follows:

self.fileMenu.addAction(self.newAction)

The menu items can be grouped by adding a separator between the items which is done as given in the following code line:

self.fileMenu.addSeparator()

Execute the program and witness the working of menus.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.97.170