analitics

Pages

Wednesday, August 21, 2019

Python Qt5 : contextMenu example.

A context menu is a menu in a graphical user interface (GUI) that appears upon user interaction, such as a right-click mouse operation.
I create the default application and I use QMenu to create this context menu with New, Open and Quit.
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu
import sys


class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Context Menu"
        self.top = 100
        self.left = 100
        self.width = 640
        self.height = 480
        self.InitWindow()


    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

    def contextMenuEvent(self, event):
        contextMenu = QMenu(self)
        new_Act = contextMenu.addAction("New")
        open_Act = contextMenu.addAction("Open")
        quit_Act = contextMenu.addAction("Quit")
        action = contextMenu.exec_(self.mapToGlobal(event.pos()))
        if action == quit_Act:
            self.close()


App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())