pythonpyqtvtkqvtkwidget

python VTK context menu not at mouse position


I am having problems with the context menu position in VTK with PyQt. The main GUI window has set the VTK widget as central widget:

from vtk_widget.vtk_widget import VTKWidget

class DySMainWindow(QtGui.QMainWindow):
    def __init__(self):

        self.vtk_widget = VTKWidget(self)
        self.setCentralWidget(self.vtk_widget)

and the VTK widget is:

import vtk
from vtk.qt4.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt4 import QtGui, QtCore, Qt


class VTKWidget(QVTKRenderWindowInteractor):
    def __init__(self, MBD_system=None, parent=None):
        super(VTKWidget, self).__init__(parent)
        #   this should show context menu
        self.AddObserver("RightButtonPressEvent", self.contextMenu)

        self.renderer = vtk.vtkRenderer()
        self.GetRenderWindow().AddRenderer(self.renderer)

        self.interactor = self.GetRenderWindow().GetInteractor()
        self.interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())

        #   camera object
        self.camera = self.renderer.GetActiveCamera()
        if self.projection == 'perspective':
            self.camera.ParallelProjectionOff()
        else:
            self.camera.ParallelProjectionOn()

        self.renderer.SetActiveCamera(self.camera)
        self.renderer.ResetCamera()
        self.renderer.SetBackground(0, 0, 0)
        self.interactor.Initialize()

    def contextMenu(self, caller, event):
        pos = self.interactor.GetEventPosition()

        menu = QtGui.QMenu(parent=self)
        menu.addAction(self.tr("Edit object"))

        menu.exec_(self.mapToGlobal(QtCore.QPoint(pos[0], pos[1])))

Any help solving this would be appreciated.


Solution

  • The contextmeny event method takes a point as an input. If we assume that your menu is called qMenuVTK and you have a parent window, the following should work:

    In your rightbuttonpressevent add the following:

    self.parent.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
    self.parent.customContextMenuRequested.connect(self.onContextMenu)
    

    And the method event will look like:

    def onContextMenu(self, point):
       self.qMenuVTK.exec_(self.parent.mapToGlobal(point))