user3419537 user3419537 - 1 month ago 7
Python Question

QMenu displays incorrectly when setParent called

I want to create a function to build a context menu that can be dynamically added to a window's menubar. Consider the following minimal example for adding a simple QMenu:

from PyQt5 import QtWidgets

class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
menu = QtWidgets.QMenu('Menu', parent=self)
act1 = menu.addAction('Action 1')
act2 = menu.addAction('Action 2')
self.menuBar().addMenu(menu)

app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()


enter image description here

This works as expected. Note that setting the parent for the QMenu is required for it to show up.




Now, if I break the menu code out into its own function and set the parent explicitly, I get the following. What's going on here?

from PyQt5 import QtWidgets

def createMenu():
menu = QtWidgets.QMenu('Menu')
act1 = menu.addAction('Action 1')
act2 = menu.addAction('Action 2')
return menu

class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
menu = createMenu()
menu.setParent(self)
self.menuBar().addMenu(menu)

app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()


enter image description here

Answer

The way you're calling setParent resets the window flags, so do this instead:

    menu.setParent(self, menu.windowFlags())