QMenu for push button lifetime issue
Summary
While doing tests to check whether PySide2 could be used, an issue has been found with the handling of QMenu when used in a helper function to generate a QPushButton, the related QMenu and QActions.
On return of the method, the QMenu object is destroyed with PySide2 while not with PyQt5.
This is likely related to the fact that QPushButton::setMenu does not take ownership of the QMenu. So it likely is garbage collected at the end of the method.
Steps to reproduce
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QAction
from PySide2.QtWidgets import QMenu
from PySide2.QtWidgets import QPushButton
def build_button_with_menu():
button = QPushButton("The button")
menu = QMenu("The menu")
button.setMenu(menu)
action = menu.addAction("The action")
return button, action
app = QApplication(sys.argv)
button, action = build_button_with_menu()
action.triggered.connect(app.quit)
sys.exit(app.exec_())
What is the current bug behavior?
This will trigger a property error saying that triggered has no connect property. Checking the action itself will show the correct type but the signal object related methods will be missing.
What is the expected correct behavior?
No error, the connection gets created, the button is shown and when clicking on the action, the application should stop.
Possible fixes
The fix is to give the QMenu a parent, in this case, the button itself, so its lifetime doesn't end with the end of the method.