user6584717
user6584717

Reputation:

NameError: global name 'QContextMenuEvent' is not defined

I want to add a right click menu.

def contextMenuEvent(self,event):
    global posX
    global posY
    global selections,scan_widget

    if event.reason() == QContextMenuEvent.Mouse:
        menu = QMenu(self)
        clear = menu.addAction('Clear')

        for i in selections:
            self.buttonLabels.append(menu.addAction(i))

        deleteBox = menu.addAction('Delete Box')
        changeId = menu.addAction('Change Id')
        cancel = menu.addAction('Cancel')
        action = menu.exec_(self.mapToGlobal(event.pos()))
        for i,key in enumerate(self.buttonLabels):
            if action == key:
                self.annotClass = selections[i]
                self.annotEnabled = True
        if action == deleteBox:
            self.deleteEnabled = True
        elif action == changeId:
            #Call the textbox
            self.newBoxId = textBox()
            self.newBoxId.setGeometry(QRect(500, 100, 300, 100))
            self.newBoxId.show()
        elif action == cancel:
            pass
        elif action == clear:
            self.annotClass = 'Clear'
            self.annotEnabled = True

        self.posX_annot = event.pos().x()
        self.posY_annot = event.pos().y()

        posX = event.pos().x()
        posY = event.pos().y()

        self.repaint()
        self.buttonLabels = []
    self.annotEnabled = False

But give me back this error:

NameError: global name 'QContextMenuEvent' is not defined

Then, I added QContextMenuEvent as import:

from PyQt5.QtWidgets import (QApplication, QComboBox, QHBoxLayout, QPushButton,QSizePolicy, QVBoxLayout, QWidget,QLineEdit, QInputDialog, QMenu,QContextMenuEvent)

But,

ImportError: cannot import name QContextMenuEvent

What am I doing wrong?

Upvotes: 0

Views: 662

Answers (2)

ham
ham

Reputation: 716

From what I googled, QContextMenuEvent class resides in the QtGui module which can be imported from PyQt5

from PyQt5.QtGui import QContextMenuEvent

Upvotes: 2

user6584717
user6584717

Reputation:

I replaced

if event.reason() == QContextMenuEvent.Mouse:

with

if event.button == Qt.RightButton:

Upvotes: 0

Related Questions