ウィンドウのメニューバーに動的に追加できるコンテキスト メニューを作成する関数を作成したいと考えています。単純な 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_()
これは期待どおりに機能します。QMenu を表示するには、その親を設定する必要があることに注意してください。
ここで、メニュー コードを独自の関数に分割し、親を明示的に設定すると、次のようになります。何が起きてる?
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_()