pythonpyqtpyqt5qmenu

QMenu created in a widget outside of my main Window doesn't appear


I've created a QMenu in a widget outside of my main window, but when I try to show it on my Application it simply doesn't appear.

If I create the exact same QMenu in my main window class it appears without any issue.

from PyQt5.QtWidgets import (
    QApplication,
    QHBoxLayout,
    QWidget,
    QPushButton,
    QMenu,
    QAction
)
from PyQt5 import QtCore


class testWidget(QWidget):
    
    def __init__(self):
        menu = QMenu()
        action = QAction("Test", checkable = True)
        menu.addAction(action)
        menu.addSeparator()
        self.menu = menu
    

class Window(QWidget):
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Test pricer")
        self.mainLayout = QHBoxLayout()
        self.setLayout(self.mainLayout)
        self.resize(900, 600)
        
        self.button = QPushButton("Show menu")
        self.button.clicked.connect(self.showMenu)
        self.mainLayout.addWidget(self.button)
        
        self.testWidget = testWidget()
        
    
    def showMenu(self):
        print(self.testWidget.menu.actions())
        #self.testWidget.menu.setParent(self)
        self.testWidget.menu.exec_(QtCore.QPoint(200, 200))
        

if __name__ == "__main__":
    app = 0
    app = QApplication([])
    window = Window()
    window.show()
    app.exec_()

I tried changing the parent of the menu to the main window but that doesn't solve the problem either.

Would anyone know a way to show the menu while still creating it in another widget?


Solution

  • The QMenu is shown but not the item "Test" so the window is very small. "Test" is not displayed because QAction is removed since it is a local variable and no other variable takes ownership. There are 2 solutions: