Skip to content

[PyQt5] How to allow users to right-click to open a menu option

As mentioned in the title, today I want to record the common action of right-click and open a menu option. Of course it is not necessary to use the right button but it is relatively common.

It’s hard to explain, it’s better to demo it in practice:

This is a desktop gadget I wrote, specially placed on the desktop to display the time and date
Right-click on the interface, and the option menu will be displayed

That’s roughly the case. So today, let’s record how to write such a program!


QMenu

Basically, to complete this function, the most important thing is to create your own QMenu object. The following is a simple Example:

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class MainWindow(QWidget):
     def __init__(self):
         super(MainWindow, self).__init__()
         self.resize(400, 300)
         self.setWindowTitle('Main Window')

         # Menu
         self.setContextMenuPolicy(Qt.CustomContextMenu)
         self.customContextMenuRequested.connect(self.right_menu)

     def right_menu(self, pos):
         menu = QMenu()

         # Add menu options
         hello_option = menu.addAction('Hello World')
         goodbye_option = menu.addAction('GoodBye')
         exit_option = menu.addAction('Exit')

         # Menu option events
         hello_option.triggered.connect(lambda: print('Hello World'))
         goodbye_option.triggered.connect(lambda: print('Goodbye'))
         exit_option.triggered.connect(lambda: exit())

         # Position
         menu.exec_(self.mapToGlobal(pos))


if __name__ == '__main__':
     app = QApplication([])
     window = MainWindow()
     window.show()
     sys.exit(app.exec_())



Output:

It looks like nothing, but this is our main interface
Right-click to display options

Since I have already written the function of the options, when I press Hello World, it will print Hello World, when I press GoodBye, it will print Goodbye, and when I press Exit, it will actually leave.

For detailed code operation, please directly refer to the code above.


References

Leave a ReplyCancel reply

Click to Copy
Exit mobile version