2

我希望能够在 QGraphicsScene 中拖动 QGraphicsItem 的实例,并在用户停止拖动时调用自定义代码。

我可以使用以下完整的工作示例使图形项可拖动(使用 PyQt。C++ 用户只需阅读selfthis

import sys
from PyQt4 import QtGui, QtCore

class MainWindowUi(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.scene = Scene(0, 0, 300, 300, self)
        self.view = QtGui.QGraphicsView()
        self.setCentralWidget(self.view)
        self.view.setScene(self.scene)
        self.scene.addItem(Square(0,0,50,50))

class Scene(QtGui.QGraphicsScene):

    def mousePressEvent(self, e):
        print("Scene got mouse press event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsScene.mousePressEvent(self, e)

    def mouseReleaseEvent(self, e):
        print("Scene got mouse release event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsScene.mouseReleaseEvent(self, e)

    def dragMoveEvent(self, e):
        print('Scene got drag move event')

class Square(QtGui.QGraphicsRectItem):
    def __init__(self, *args):
        QtGui.QGraphicsRectItem.__init__(self, *args)
        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)

    def mousePressEvent(self, e):
        print("Square got mouse press event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsRectItem.mousePressEvent(self, e)

    def mouseReleaseEvent(self, e):
        print("Square got mouse release event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsRectItem.mouseReleaseEvent(self, e)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MainWindowUi()
    win.show()
    sys.exit(app.exec_())

当我们点击正方形时,我们会看到来自场景和正方形的打印语句。方块可以拖动。当我们释放鼠标时,我们会看到来自 Scene 和 Square 的打印语句。

问题是:在拖动过程中和拖动完成时执行了哪些方法?例如,当我释放鼠标时,需要在示例中添加什么来打印正方形的位置?

4

0 回答 0