Add dropdown actions to Pyqt5 frame widget when right-click event is triggered

Question:

I have a Qframe widget and I already created an event triger like this

    def mousePressEvent(self, QMouseEvent):
        if QMouseEvent.button() == Qt.RightButton:
            # do what you want here
            print("Right Button Clicked")
            #showMenuAtMouseLocation()  # to be implemented

I want a small menu list to be added at the mouse location (on the widget) which contains some actions as in the image

I tried adding Qmenu to the frame widget but it doesn’t show

class TOCFrame(QFrame):
    def __int__(self):
        QFrame.__int__(self)
        self.menuBar = QMenuBar(self)
        exitMenu = self.menuBar.addMenu('remove')
        self.menuBar.show()

    def mousePressEvent(self, QMouseEvent):
        if QMouseEvent.button() == Qt.RightButton:
            # do what you want here
            print("Right Button Clicked")
            #showMenuAtMouseLocation()  # to be implemented

Asked By: Ahmad Raji

||

Answers:

You are looking for QContextMenuEvent, and the contextMenuEvent listener.

You listen for the context menu event by overriding the event listener contextMenuEvent, then you can either create the menu or use a pre-made menu and use the event’s globalPos attribute to display it at the point the mouse was clicked.

class TOCFrame(QFrame):
    def __int__(self):
        QFrame.__int__(self)
        self.menuBar = QMenuBar(self)
        exitMenu = self.menuBar.addMenu('remove')
        self.menuBar.show()

    def contextMenuEvent(self, event):
        menu = QMenu(self)
        menu.addAction("Option1")
        menu.addAction("Option2")
        menu.addAction("Option3")
        menu.exec(event.globalPos())

https://doc.qt.io/qt-6/qcontextmenuevent.html

Answered By: Alexander
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.