我正在尝试创建小型GUI应用程序,用户可以在其中绘制点和曲线。我实施了比例选项。
我想仅缩放路径,而不是缩放点的图形表示(RBNode类)。除了RBNode类之外,有没有办法扩展QGraphicsView?
我目前的方法是将RBGraphicView类(继承自QGraphicsView)中的wheelEvent方法中创建的因子属性传递到RBNode的实例中,并使用它重绘RBNode。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import math
from PySide.QtGui import *
from PySide.QtCore import *
class RBNode(QGraphicsItem):
def __init__(self, factorView = 1):
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):
self.update()
return QRectF(-5*self.factor,-5*self.factor,10*self.factor,10*self.factor)
def paint(self, painter, option, widget):
self.update()
rect = QRectF(-5*self.factor,-5*self.factor,10*self.factor,10*self.factor)
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(self,event)
def mouseReleaseEvent(self, event):
self.pressed = False
self.update()
QGraphicsItem.mouseReleaseEvent(self,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 wheelEvent(self, event):
factor = math.pow(2.0, -event.delta() / 240.0)
self.scaleView(factor)
def scaleView(self, scaleFactor):
factor = self.matrix().scale(scaleFactor, scaleFactor).mapRect(QRectF(0,0,1,1)).width()
if factor < 0.001 or factor > 1000:
return
self.scale(scaleFactor, scaleFactor)
self.factorView = factor
def rbAddItem(self, scene):
rbNode1 = RBNode(self.factorView)
rbNode1.setPos(100,100)
rbNode2 = RBNode()
rbNode2.setPos(100,100)
rbP2 = QPointF(20.0, 10.0)
rbP3 = QPointF(80.0, 30.0)
rbP4 = QPointF(90.0, 70.0)
bezierPath = QPainterPath()
bezierPath.moveTo(rbNode1.x, rbNode1.y)
bezierPath.cubicTo(rbP2.x(),rbP2.y(),rbP3.x(),rbP3.y(),rbP4.x(),rbP4.y())
myItem = QGraphicsPathItem(bezierPath)
scene.addItem(rbNode1)
scene.addItem(rbNode2)
scene.addItem(myItem)
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])