Examples of menu bar and toolbar in PyQt5

Time:2019-9-6

In this section, we learn to create status bars, menu bars and toolbars. A menu is a set of commands located in the menu bar. A toolbar has buttons that have common commands in applications. The status bar displays status information, usually under the application window.

QMainWindow

The QMainWindow class provides a main application window. This allows us to create a classic program framework with status bars, toolbars and menu bars.

Statusbar (status bar)

A status bar is a component used to display status information.


#!/usr/bin/python3
# -*- coding:utf-8 -*- 

  import sys
  from PyQt5.QtWidgets import QMainWindow, QApplication

  class Example(QMainWindow):

    def __init__(self):
      super().__init__()

      self.initUI()

    def initUI(self):
      self.statusBar().showMessage("Ready")

      self.setGeometry(300,300,250,150)
      self.setWindowTitle("StatusBar")
      self.show()

  if __name__ == '__main__':
    app = QApplication(sys.argv)

    ex = Example()

    sys.exit(app.exec_())

The status bar is created with the help of the QMainWindow component.

self.statusBar().showMessage(“Ready”)

To get the status bar, we call the statusBar () method of the class QtGui. QMainWindow. The first call to this method creates a status bar. Subsequence calls return status bar objects. ShowMessage () displays information on the status bar.

Following is the result of the operation of this small example program:

Simple menu

The menu bar is a common component of GUI applications. He is a group of commands located on multiple menus. Mac OS treats menu bars differently. To get similar output, we can add the following line: menubar. setNativeMenubar (False).)


#!/usr/bin/python3
# -*- coding:utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow,QAction, QApplication, qApp
from PyQt5.QtGui import QIcon

class Example(QMainWindow):
  def __init__(self):
    super().__init__()

    self.initUI()

  def initUI(self):
    exitAct = QAction(QIcon('exit.png'),'&Exit',self)
    exitAct.setShortcut('Ctrl+Q')
    exitAct.setStatusTip("Exit application")
    exitAct.triggered.connect(qApp.quit)

    self.statusBar()

    menubar = self.menuBar()

    fileMenu = menubar.addMenu("&File")
    fileMenu.addAction(exitAct)

    self.setGeometry(300,300,300,200)
    self.setWindowTitle("Simple menu")
    self.show()

if __name__ == '__main__':

  app = QApplication(sys.argv)

  ex = Example()

  sys.exit(app.exec_())

In the example program above, we created a menu bar with a menu. This menu contains an action that will terminate the application if selected. Of course, a status bar was created. This action can also use Ctrl + Q shortcuts.


exitAct = QAction(QIcon("exit.png"),"&Exit",self)
exitAct.setShortcut("Ctrl+Q")
exitAct.setStatusTip("Exit application")

QAction is an abstract class that runs in menu bars, toolbars, and custom keyboard shortcuts. In the three lines above, we created a behavior using a specific icon and an’Exit’tag. Further, a shortcut key is defined for this behavior. The third line creates a status prompt that is displayed on the status bar when the mouse passes through the menu option.


exitAct.triggered.connect(qApp.quit)

When we select this particular behavior, a trigger signal is submitted. The signal is connected to the quit () method of the QApplication component. This will terminate the program.


menubar = self.menuBar()
fileMenu = menubar.addMenu("&File")
fileMenu.addAction(exitAct)

The menuBar () method creates a menu bar. We created a file button using addMenu () and added an action using the addAction () method.

Below is a screenshot of this small example:

![enter description here][2

Submenu

A submenu is a menu located in another menu.


#!/usr/bin/python3
# -*- coding:utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, QMenu, QApplication

class Example(QMainWindow):

  def __init__(self):
    super().__init__()

    self.initUI()

  def initUI(self):
    menubar = self.menuBar()
    fileMenu = menubar.addMenu("File")

    impMenu = QMenu("Import",self)
    impAct = QAction("Import mail",self)
    impMenu.addAction(impAct)

    newAct = QAction("New", self)

    fileMenu.addAction(newAct)
    fileMenu.addMenu(impMenu)

    self.setGeometry(300,300,300,200)
    self.setWindowTitle("Submenu")

    self.show()

if __name__ == '__main__':

  app = QApplication(sys.argv)

  ex = Example()

  sys.exit(app.exec_())

In this example, we have two menu options: one in the file menu and the other in the Import submenu of the file.


impMenu = QMenu("Import", self)

The new menu is created using QMenu.


impAct = QAction("Import mail", self)
impMenu.addAction(impAct)

An action is added to the submenu by using addAction ().

Options menu

In the following example, we create a button that can be selected or not.


#!/usr/bin/python3
# -*- coding:utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QAction

class Example(QMainWindow):

  def __init__(self):
    super().__init__()

    self.initUI()

  def initUI(self):

    self.statusbar = self.statusBar()
    self.statusbar.showMessage("Ready")

    menubar = self.menuBar()
    viewMenu = menubar.addMenu("View")

    viewStatAct = QAction("View statusbar",self,checkable=True)
    viewStatAct.setStatusTip("View statusbar")
    viewStatAct.setChecked(True)
    viewStatAct.triggered.connect(self.toggleMenu)

    viewMenu.addAction(viewStatAct)

    self.setGeometry(300,300,300,200)
    self.setWindowTitle("Check menu")
    self.show()

  def toggleMenu(self,state):
    if state:
      self.statusbar.show()
    else:
      self.statusbar.hide()


if __name__ == "__main__":
  app = QApplication(sys.argv)

  ex = Example()

  sys.exit(app.exec_())

This code example creates a view menu with an action. This behavior shows or hides the status bar. Menu options are selected when the status bar is visible.


viewStatAct = QAction('View statusbar', self, checkable=True)

Using the checkable option, we created an optional menu.


viewStatAct.setChecked(True)

Because the status bar is visible at the beginning, we use the setChecked () method to set the behavior.


def toggleMenu(self, state):
  if state:
    self.statusbar.show()
  else:
    self.statusbar.hide()

Depending on the status selected by the behavior, we set whether the status bar is displayed or not.

Context menu

A context menu, also known as a pop-up menu, is a list of commands that appear in some contexts. For example, in an Opera web browser, when you right-click on a web page, we get a context menu. Here we can reload a page, rollback, or view the page source code. If we right-click on a toolbar, we will get another context menu for the administration toolbar.


#!/usr/bin/python3
# -*- coding:utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, qApp,QMenu,QApplication

class Example(QMainWindow):

  def __init__(self):
    super().__init__()

    self.initUI()

  def initUI(self):
    self.setGeometry(300,300,300,200)
    self.setWindowTitle("Context menu")

    self.show()

  def contextMenuEvent(self,event):
    cmenu = QMenu(self)

    newAct = cmenu.addAction("New")
    opnAct = cmenu.addAction("Open")
    quitAct = cmenu.addAction("Quit")
    action = cmenu.exec_(self.mapToGlobal(event.pos()))

    if action == quitAct:
      qApp.quit()

if __name__ == '__main__':
  app = QApplication(sys.argv)

  ex = Example()

  sys.exit(app.exec_())

In order to be able to use context menus, we must re-integrate the contextMenuEvent () method.


action = cmenu.exec_(self.mapTpGlobal(event.pos()))

The context menu is displayed by the exec_() method. They get the coordinates of the mouse pointer from the event object. The mapToGlobal () method passes the component coordinates to the global screen coordinates.


if action == quitAct:
  qApp.quit()

If the behavior returned from the context menu equals the exit behavior, the program is terminated.

toolbar

In an application, the menu bar organizes all commands. The toolbar provides fast access to common commands.


#!/usr/bin/python3
# -*- coding:utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp,QApplication
from PyQt5.QtGui import QIcon

class Example(QMainWindow):

  def __init__(self):
    super().__init__()

    self.initUI()

  def initUI(self):

    exitAct = QAction(QIcon("exit.png"),"Exit",self)
    exitAct.setShortcut("Ctrl+Q")
    exitAct.triggered.connect(qApp.quit)

    self.toolbar = self.addToolBar("Exit")
    self.toolbar.addAction(exitAct)

    self.setGeometry(300,300,300,200)
    self.setWindowTitle("Toolbar")
    self.show()


if __name__ == '__main__':
  app = QApplication(sys.argv)

  ex = Example()

  sys.exit(app.exec_())

In the example above, we created a simple toolbar. The toolbar has a tool behavior, an exit behavior, and terminates the program when triggered.


  exitAct = QAction(QIcon("exit.png"),"Exit",self)
    exitAct.setShortcut("Ctrl+Q")
    exitAct.triggered.connect(qApp.quit)

Like the menu bar in the example above, we created a behavior object. The object has a label, icon and a shortcut. A quit () method in Qt. QMainWindow is connected to the trigger signal.


   self.toolbar = self.addToolBar("Exit")
   self.toolbar.addAction(exitAct)

The toolbar is created by addToolBar (). We use the addAction () method to add an action object to the toolbar.

Put them together

In the final example, we will create a menu bar, a toolbar and a status bar. We will also create a central component.


#!/usr/bin/python3
# -*- coding:utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction,QApplication
from PyQt5.QtGui import QIcon

class Example(QMainWindow):

  def __init__(self):
    super().__init__()

    self.initUI()

  def initUI(self):

    textEdit = QTextEdit()
    self.setCentralWidget(textEdit)

    exitAct = QAction(QIcon("exit.png"),"Exit",self)
    exitAct.setShortcut("Ctrl+Q")
    exitAct.setStatusTip("Exit application")
    exitAct.triggered.connect(self.close)

    self.statusBar()

    menubar = self.menuBar()
    fileMenu = menubar.addMenu("&File")
    fileMenu.addAction(exitAct)

    toolbar = self.addToolBar("Exit")
    toolbar.addAction(exitAct)

    self.setGeometry(300,300,350,250)
    self.setWindowTitle("Main Window")
    self.show()

if __name__ == "__main__":

  app = QApplication(sys.argv)

  ex = Example()

  sys.exit(app.exec_())

Here, we create a text editing component. We also set it up as the central component of QMainWindow. The central component is divided into all the remaining spaces.

In this chapter, we learned about the menu bar, toolbar and status bar, as well as a main program window. Hope to give you a reference, but also hope that you support more developpaer.

Recommended Today

Resolving Time Zone Errors with Docker

1. The correct time zone in China is set to CST, i.e.China Standard TimeIn usedockerstart-upJenkinsWhen mirroring, the settings for mirroring are usuallyCoordinated Universal Time。 So add parameters at startup -v /etc/localtime:/etc/localtimeMount the local time zone to the mirror, so that the mirror gets the correct time zone. Then go to Jenkins and fill in the […]