Search code examples
python-3.xqtpyside2

QMenu only showing on QPushButton when calling QPushButton.menu()


With the code from this example, I don't get the menu on the button. It will just remain a simple button.

    menu = QMenu()
    Act1 = QtWidgets.QAction("Action 1", menu)
    Act1.setCheckable(True)
    Act2 = QtWidgets.QAction("Action 2", menu)
    Act2.setCheckable(True)
    menu.addAction(Act1)
    menu.addAction(Act2)

    btn = QtWidgets.QPushButton("Multiselection")
    btn.setMenu(menu)

But it somehow works when calling btn.menu() after the last line above. Unfortunately, this line will also cause python to stop working upon closing the app.

PyCharm output: Process finished with exit code -1073741819 (0xC0000005)

If it helps: I'm using PySide2 version 2.0.0


Solution

  • QPushButton.setMenu does not take ownership of the menu. You need to parent the menu: menu = QMenu(yourParentQObjectDescendent). In your code, the menu will be destroyed after the enclosing method returns.

    0xC0000005 is an Access Violation. Wrongly unparented QObjects and descendents are a frequent cause of it in PyQt.