PySide:计算自上次调用 mouseMoveEvent 函数以来 x 轴和 y 轴的移动量

PySide : Compute the amount of movement in both x and y axis since the previous call to the mouseMoveEvent function

我是 Pyside 的新手,我需要计算自上次调用 mouseMoveEvent 函数以来 x 轴和 y 轴的移动量

思路是获取鼠标的前一个位置(A)和当前位置(B)。我们计算从 A 开始到 B

结束的向量

我的问题如下:QMouseEvent 没有 lastPos() 函数,而是 pos() 函数。因此,我无法获取鼠标的前一个位置(最后记录的位置是创建事件的视图接收到的前一个鼠标事件的位置)

在 Pygame 中,这称为 pygame.mouse.get_rel()。我怎样才能做到这一点 ?

这是一个示例代码,在按下和移动时打印鼠标的当前位置

 # -*- coding: utf-8 -*-
import sys
from PySide import  QtGui

class Frame(QtGui.QFrame):

    def __init__(self, (width, height)):
        super(Frame, self).__init__()

        self.setGeometry(0, 0, width, height)
        self.setWindowTitle('Frame')
        self.show()
        self.loop()

    def loop(self):
        while 1:
            self.update()
            QtGui.QApplication.processEvents()

    def mouseMoveEvent(self, event):
        # Get the current position of the mouse
        x, y = event.x(), event.y()
        print (x, y)


def main():
    app = QtGui.QApplication(sys.argv)
    Frame((500, 500))
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

我无法在没有 PySide 的情况下测试它,我目前无法安装它,但我 认为 你想要这样的东西(阅读 NOTE1NOTE2):

import sys
from PySide import  QtGui

class Frame(QtGui.QFrame):

    def __init__(self, (width, height)):
        super(Frame, self).__init__()

        # NOTE1: indicate if mouse was clicked
        self.clicked= False

        self.setGeometry(0, 0, width, height)
        self.setWindowTitle('Frame')
        self.show()
        self.loop()

    def loop(self):
        while 1:
            self.update()
            QtGui.QApplication.processEvents()

    def mouseMoveEvent(self, event):
        # Get the current position of the mouse
        x, y = event.x(), event.y()
        print (x, y)

    def mousePressEvent(self, event):
        # NOTE 2: track clicks, not movements
        if self.clicked:
            # calculate vector
            vector = ((self.x, self.y,), (event.x(), event.y(),))
            print "vector: %s" % str(vector)
            self.clicked = False
            return vector
        # set vector start
        self.x = event.x()
        self.y = event.y()
        self.clicked = True
        print "vector set to start from: (%d,%d)" % (self.x, self.y)
        return None

def main():
    app = QtGui.QApplication(sys.argv)
    Frame((500, 500))
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

这样你就可以设置从第一次点击到第二次点击的矢量,矢量从每次鼠标点击开始。这可能有一些错误,但思路很清楚。如果您希望鼠标跟踪移动而不是点击,请对 mouseMoveEvent.

应用相同的原则(在子类中存储最后一个位置,设置标志以查看是否应计算矢量...)

稍后我会在我的电脑上测试它。