Search code examples
pythonpython-3.xmacospyqt5qmenu

Menu Separator Does Not Show


In constructing an application menu bar for PYQT5 on MacOS, I emulate system menus that the PYQT5 back-end does not automatically create, and attempt to repair those it creates incompletely. For example, when a QMenu widget is created with the title &View, the back-end will automatically generate an "Enter Full Screen" menu option (and very helpfully manage the full screen action). However, the back end will not display a separator before the automatically-generated "Enter Full Screen" item. Every attempt to add the separator before sys.exit(qApp.exec_()) is called proved futile.

self.view_menu = QtWidgets.QMenu('&View', self)
self.view_menu.addAction('&Refresh Chart', self.create_plot, QtCore.Qt.CTRL + QtCore.Qt.Key_R)
self.view_menu.addAction('&Update Chart', self.file_open_update, QtCore.Qt.CTRL + QtCore.Qt.Key_U)
self.view_menu.addSeparator()  # <---- This separator is not displayed.
self.menuBar().addMenu(self.view_menu)

View menu with no separator


Solution

  • In order to get the separator to display above a system-generated menu item, an additional (temporary) menu item needs to be generated when the menu bar is first constructed, and removed before the menu bar is first displayed.

    self.view_menu = QtWidgets.QMenu('&View', self)
    self.view_menu.addAction('&Refresh Chart', self.create_plot, QtCore.Qt.CTRL + QtCore.Qt.Key_R)
    self.view_menu.addAction('&Update Chart', self.file_open_update, QtCore.Qt.CTRL + QtCore.Qt.Key_U)
    self.view_menu.addSeparator()
    self.__menu_temp = self.view_menu.addAction('temp')  # <---- Temporary menu item
    self.view_menu.aboutToShow.connect(self.view_menu_build)  # <---- Remove item before menu is displayed
    self.menuBar().addMenu(self.view_menu)
    
    def view_menu_build(self):
        """ Remove temporary menu item """
        self.view_menu.removeAction(self.__menu_temp)
    
    

    View menu with separator