python VTK上下文菜单不在鼠标位置

时间:2016-07-25 09:25:48

标签: python pyqt vtk qvtkwidget

我在使用PyQt的VTK中遇到上下文菜单位置问题。主GUI窗口将VTK小部件设置为中央小部件:

from vtk_widget.vtk_widget import VTKWidget

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

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

VTK widget是:

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])))

任何帮助解决这个问题都将受到赞赏。

1 个答案:

答案 0 :(得分:2)

contextmeny事件方法将一个点作为输入。如果我们假设您的菜单名为qMenuVTK且您有父窗口,则以下内容应该有效:

在rightbuttonpressevent中添加以下内容:

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

方法事件将如下所示:

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