我正在编写一个应用程序,该应用程序允许用户通过单击空白区域将图像放置在 QGraphicsScene(包含在 QGraphicsView 中)上,然后使用 mousemoveevent 移动它们。图像是使用子类 QGraphicsPixmapItem 创建的。
问题出在:第一次尝试移动项目时按预期工作。但是,对于所有后续移动,所选项目会立即跳转到场景的左上角。这是代码:
import sys
from PySide import QtGui,QtCore
class TestPixmapItem(QtGui.QGraphicsPixmapItem):
def __init__(self, imagename, position, parent=None):
QtGui.QGraphicsPixmapItem.__init__(self, parent)
px = QtGui.QPixmap(imagename)
self.setPixmap(px)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
# set position
self.setPos(position.x(),position.y())
def mouseReleaseEvent(self,e):
self.setSelected(False)
def mouseMoveEvent(self, e):
QtGui.QGraphicsPixmapItem.mouseMoveEvent(self, e)
class GfxScene(QtGui.QGraphicsScene):
def __init__(self, parent=None):
#build parent user interface
super(GfxScene, self).__init__(parent)
def mousePressEvent(self, e):
if(self.itemAt(e.scenePos().x(),e.scenePos().y()) == None):
pixmapItem = TestPixmapItem('test.png',e.scenePos())
self.addItem(pixmapItem)
else:
QtGui.QGraphicsScene.mousePressEvent(self,e);
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
scene = GfxScene(self)
scene.setSceneRect(QtCore.QRect(0, 0, 800, 800))
view = QtGui.QGraphicsView()
view.setScene(scene)
view.setSceneRect(scene.sceneRect())
#view.setGeometry(QtCore.QRect(0, 0, 800, 800))
self.setCentralWidget(view)
def main():
#This function means this was run directly, not called from another python file.
app = QtGui.QApplication.instance()
if app == None:
app = QtGui.QApplication(sys.argv)
myapp = MainForm()
myapp.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
任何帮助,将不胜感激!