简体   繁体   English

PySide:可移动项目的位置在鼠标事件时重置

[英]PySide: Position of movable item resets on mouse event

I have problem with PySide (I'm still rookie in programming). 我对PySide有问题(我仍然是编程方面的新手)。 I created custom QGraphicsItem called RBNode. 我创建了名为RBNode的自定义QGraphicsItem。 It should stay in the position where mouseReleaseEvent has happend. 它应保持在发生mouseReleaseEvent的位置。 I don't know why but when I'm trying to move the instance of RBNode class more than once, the position of this instance resets. 我不知道为什么,但是当我尝试多次移动RBNode类的实例时,此实例的位置将重置。 How can I avoid reseting position? 如何避免重置位置? Thanks in advance for your help. 在此先感谢您的帮助。

#!/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])

You forgot self as parameter in the calls to mousePressEvent, mouseReleaseEvent of the super classes. 您在对超类的mousePressEvent和mouseReleaseEvent的调用中忘记了作为参数的自身。

    QGraphicsItem.mousePressEvent(self, event)

    QGraphicsItem.mouseReleaseEvent(self, event)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM