QMenu displays incorrectly when setParent called
<p>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:</p>

<pre><code>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_()
</code></pre>

<p><a href="https://i.stack.imgur.com/4WqDq.png" rel="nofollow"><img src="https://i.stack.imgur.com/4WqDq.png" alt="enter image description here"></a></p>

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

<hr>

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

<pre><code>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_()
</code></pre>

<p><a href="https://i.stack.imgur.com/tDNcG.png" rel="nofollow"><img src="https://i.stack.imgur.com/tDNcG.png" alt="enter image description here"></a></p>

<p>The way you're calling <code>setParent</code> resets the window flags, so do this instead:</p>

<pre><code>    menu.setParent(self, menu.windowFlags())
</code></pre>

python qt pyqt qmenu qmenubar