1

I set a stylesheet on my entire window in which the background of a QMenu should be green. However, when I create the menu (self.project_menu in the MenuBar class), it does not inherit the stylesheet. If I instead use self.project_menu = self.addMenu("Project") it works fine. Is there a reason why it behaves like this?

class MenuBar(QtWidgets.QMenuBar):
    def __init__(self):
        super(MenuBar, self).__init__()
        self.project_menu = QtWidgets.QMenu("Project")
        self.addMenu(self.project_menu)
        self.create_new_action = self.project_menu.addAction("Create New Project")


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.widget = QtWidgets.QWidget()
        self.setCentralWidget(self.widget)
        self.mainLayout = QtWidgets.QVBoxLayout()
        self.widget.setLayout(self.mainLayout)

        self.menu_bar = MenuBar()
        self.setMenuBar(self.menu_bar)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    win = MainWindow()
    win.setStyleSheet("""
        QMenu{
            background: green;
        }
    """)
    win.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

2

Explanation:

When the setStyleSheet method is used is propagated from parents to children, in the case of using:

self.project_menu = self.addMenu("Project")

The parent of the QMenu is the QMenuBar(you can check with: assert self.project_menu.parent() == self), and the QMenuBar is a child of the window so the stylesheet will be propagated.

Instead if you use:

self.project_menu = QtWidgets.QMenu("Project")
self.addMenu(self.project_menu)

The QMenu does not have a parent so the stylesheet will not be propagated.

Solution:

The solution is to set the QMenuBar as the parent of the QMenu:

self.project_menu = QtWidgets.QMenu("Project", self)
self.addMenu(self.project_menu)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241