PySide:可移动项重置在鼠标事件

时间:2017-03-08 22:29:30

标签: python python-2.7 user-interface mouseevent pyside

我遇到了PySide的问题(我还是编程中的新手)。我创建了名为RBNode的自定义QGraphicsItem。它应该保持在mouseReleaseEvent发生的位置。我不知道为什么,但是当我试图多次移动RBNode类的实例时,此实例的位置会重置。我怎样才能避免重置位置? 在此先感谢您的帮助。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PySide.QtGui import *
from PySide.QtCore import *

class RBNode(QGraphicsItem):
    def __init__(self, factorView = None):
        super(RBNode, self).__init__()
        self.factor = factorView
        self.pressed = False
        self.x = self.pos().x()
        self.y = self.pos().y()
        self.setFlag(QGraphicsItem.ItemIsMovable)

    def boundingRect(self):
        return QRectF(-50,-50,100,100)

    def paint(self, painter, option, widget):
        rect = QRectF(-50,-50,100,100)

        if self.pressed:
            painter.setBrush(Qt.red)
        else:
            painter.setBrush(Qt.darkGray)

        painter.drawEllipse(rect)

    def mousePressEvent(self, event):
        self.pressed = True
        self.update()
        QGraphicsItem.mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        self.pressed = False
        self.update()
        QGraphicsItem.mouseReleaseEvent(event)


class RBGraphicView(QGraphicsView):
    def __init__(self):
        super(RBGraphicView, self).__init__()
        self.factorView = 1

        self.initScene()
        self.initGui()

    def initGui(self):
        self.setWindowTitle("A Simple Animation")
        self.show()

    def initScene(self):
        self.rbScene = QGraphicsScene(self)
        self.rbAddItem(self.rbScene)
        self.setScene(self.rbScene)

    def rbAddItem(self, scene):

        rbNode1 = RBNode(self.factorView)
        rbNode1.setPos(100,100)
        scene.addItem(rbNode1)


if __name__ == '__main__':
    try:
        myApp = QApplication(sys.argv)
        myView = RBGraphicView()
        myApp.exec_()
        sys.exit(0)

    except NameError:
        print("Name Error:", sys.exc_info()[1])

    except SystemExit:
        print("Closing Window...")

    except Exception:
        print(sys.exc_info()[1])

1 个答案:

答案 0 :(得分:0)

你在超级类的mousePressEvent,mouseReleaseEvent的调用中忘记了self作为参数。

    QGraphicsItem.mousePressEvent(self, event)

    QGraphicsItem.mouseReleaseEvent(self, event)