4

I'm new to python and pyqt5/pyqtgraph. Trying to add an action/item to the context menu of a PlotWidget using the code below. The New_Item appears overlaid on top of the "View All" item in the context menu [have picture, but as a new user, not allowed to post it :-(] instead of above it. I think I'm adding a new context menu (instead of accessing the default context menu and adding to it). I'd appreciate guidance with figuring out what I'm doing wrong. Thanks in advance for the help!

from PyQt5 import QtWidgets
import pyqtgraph as pg
    
class Plot(pg.PlotWidget):
           
    def contextMenuEvent(self, event):
        menu = QtWidgets.QMenu(self)
        someAction = menu.addAction('New_Item')
    
        res = menu.exec_(event.globalPos())
        if res == someAction:
            print('Hello')
    
if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    plot = Plot()
    plot.show()
    sys.exit(app.exec_())][1]
D.L
  • 4,339
  • 5
  • 22
  • 45
TM 1001
  • 41
  • 2

1 Answers1

0

Your code saved my day! I was also confused about how to create a customized context menu. Many thanks!

If you are still working out this issue,

class Plot(pg.PlotWidget):

    def __init__(self):
        super().__init__()
        self.setMenuEnabled(False)

    def contextMenuEvent(self, event):
        menu = QtWidgets.QMenu(self)
        someAction = menu.addAction('New_Item')

        res = menu.exec_(event.globalPos())
        if res == someAction:
            print('Hello')


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    plot = Plot()
    plot.show()
    app.exec_()

Use setMenuEnabled(False) to disable the default context menu. It just does nothing to your customized context menu and everything works fine.