Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向QGraphicsItem添加上下文菜单的正确方法?_Python_Qt_Python 2.7_Pyqt4 - Fatal编程技术网

Python 向QGraphicsItem添加上下文菜单的正确方法?

Python 向QGraphicsItem添加上下文菜单的正确方法?,python,qt,python-2.7,pyqt4,Python,Qt,Python 2.7,Pyqt4,我正在使用PyQt编写的编辑器,我希望能够在我的qgraphicscene中打开连接到我的QGraphicsItem:s的上下文菜单。我已经搜索了将上下文菜单与图形项结合使用的解决方案,并找到了一个打开工作上下文菜单的解决方案,该菜单可以触发这些项的操作。下面是一个简单的工作示例: from PyQt4 import QtGui, QtCore class TestItem(QtGui.QGraphicsItem): def __init__(self, parent=None, s

我正在使用PyQt编写的编辑器,我希望能够在我的
qgraphicscene
中打开连接到我的
QGraphicsItem
:s的上下文菜单。我已经搜索了将上下文菜单与图形项结合使用的解决方案,并找到了一个打开工作上下文菜单的解决方案,该菜单可以触发这些项的操作。下面是一个简单的工作示例:

from PyQt4 import QtGui, QtCore

class TestItem(QtGui.QGraphicsItem):

    def __init__(self, parent=None, scene=None):
        super(TestItem, self).__init__(parent, scene)
        self.setFlags(self.ItemIsMovable | self.ItemIsSelectable)

    def boundingRect(self):
        return QtCore.QRectF(0,0,50,50)

    def paint(self, painter, options, widget=None):
        painter.drawRect(self.boundingRect())

    def contextMenuEvent(self, event):
        menu = QtGui.QMenu()
        testAction = QtGui.QAction('Test', None)
        testAction.triggered.connect(self.print_out)
        menu.addAction(testAction)
        menu.exec_(event.screenPos())

    def print_out(self):
        print 'Triggered'

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    window = QtGui.QWidget()
    scene = QtGui.QGraphicsScene()

    item = TestItem(scene=scene)
    view = QtGui.QGraphicsView(scene)

    layout = QtGui.QVBoxLayout()
    layout.addWidget(view)
    window.setLayout(layout)
    window.show()
    sys.exit(app.exec_())
我的问题是,有时在打开关联菜单后,当项目在场景中移动时,项目的位置会发生移动。有时,这种转换非常大,这非常烦人,给编辑器带来了一种非常麻烦的外观。我还没能找到问题的原因

在不产生这种行为的
qgraphicscene
中,是否有更好的方法使用上下文菜单?我想能够打开菜单,这取决于什么类型的项目是点击,并认为这可能是一个整洁的解决方案