Create event clicking on context menu with python pyqt5

632 Views Asked by At

Am working with PyQt5, and I have a window app, I already have some functions and classes, and I implemented that when the user click Mouse Right-click it shows a context menu.

What I need is: I want to make a unit test for the code, so I want to test the right click which will open the context menu and after that I must test if the user click on it, it should do something like removing the points.

But my problem is I can't make an event that will click on that context menu and take action, because what I think is it is not in the widget so I can't make an event click on the point that the context menu are in, I tried it but it doesn't work.

So any ideas, how to make an event click on or pass or anything just made the action taken and run the code after context menu opened?

NOTE: I'm using QEvent for testing, Since am working with QWidget and QApllication PyQt5 python 3.7.

Here is the test event that opened the context menu:

    point = QPointF(30, 30) #For example this will open the context menu at that point
    e = QMouseEvent(QMouseEvent.MouseButtonPress, point, Qt.RightButton, Qt.NoButton, Qt.NoModifier)  #Right Click
    self.canvas.contextMenuEvent(e)

This is from canvas class:

    def contextMenuEvent(self, ev):
    """
    overrides the original contextMenuEvent function
    :param ev: <QEvent>
    :return: None
    """
    self.current_tool.context_menu(ev)

And this is from the current tool function:

    def context_menu(self, e):
    menu = QMenu(self.canvas)
    delete_whole_polygon_act = menu.addAction("Delete Area?")
    action = menu.exec_(self.canvas.mapToGlobal(e.pos()))
    if action == delete_whole_polygon_act: 
        self.delete_polygon(e.pos())
0

There are 0 best solutions below