NameError:未定义全局名称“QContextMenuEvent”

时间:2016-09-01 08:41:39

标签: python menu pyqt5

我想添加一个右键菜单。

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

但请回复此错误:

  

NameError:未定义全局名称“QContextMenuEvent”

然后,我将QContextMenuEvent添加为import:

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

但是,

  

ImportError:无法导入名称QContextMenuEvent

我做错了什么?

2 个答案:

答案 0 :(得分:2)

根据我用Google搜索,QContextMenuEvent类位于QtGui模块中,该模块可以从PyQt5导入

from PyQt5.QtGui import QContextMenuEvent

答案 1 :(得分:0)

我替换了

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

if event.button == Qt.RightButton: