PDA

View Full Version : Drawing shapes using GraphicsView, GraphicsScene and GraphicsItem(s)



HelderC
1st October 2012, 13:16
Hi.

If I want to create a kind of "Ms Paint" using GraphicsView, GraphicsScene and Items, which class I have to reimplement to get mousepress and mousemove events? GraphicsView or Scene?

I tried to use Scene, but even with it in 600x500 WidthxHeight ever place that I click the coordinates are the same 0,0 and the follow code dont draw any thing, in this case, a line.


from PyQt4.QtGui import *
from PyQt4.QtCore import *

class GraphicsScene(QGraphicsScene):
def __init__(self, parent = None):
super(GraphicsScene, self).__init__(parent)

self.setSceneRect(0, 0, 600, 500)
self.setBackgroundBrush(QColor(242, 251, 235))


def mousePressEvent(self, e):
self.pointBegin = self.pointEnd = e.pos()

self.line = QGraphicsLineItem(QLineF(self.pointBegin, self.pointEnd))
self.line.setFlags(QGraphicsItem.ItemIsMovable)

self.addItem(self.line)

def mouseMoveEvent(self, e):
self.pointEnd = e.pos()

self.line.setLine(QLineF(self.pointBegin, self.pointEnd))


def mouseReleaseEvent(self, e):
self.line.setLine(QLineF(self.pointBegin, self.pointEnd))

norobro
2nd October 2012, 00:27
Have you looked in the docs (http://qt-project.org/doc/qt-4.8/qgraphicsscenemouseevent.html#pos)?

HelderC
2nd October 2012, 00:31
Yes, I did. The "e" param at mouseXEvent is all of that type.

My question is: "...which class I have to reimplement to get mousepress and mousemove events?"

Thank you anyway.

norobro
2nd October 2012, 00:46
My answer is, as described in the docs: change e.pos() to e.scenePos()

And you're welcome.

HelderC
2nd October 2012, 02:15
Sorry man, but I'm a little confuse.

You want to say I have to reimplement the GraphicsView, instead GraphicsScene and use e.scenePos() instead e.pos() ??

Is that correct?

wysota
2nd October 2012, 02:23
My question is: "...which class I have to reimplement to get mousepress and mousemove events?"
It can be either QGraphicsView, QGraphicsScene or one of QGraphicsItem subclasses, depending on what you want to do with the event.

You are getting 0 because calling pos() doesn't make sense in context of the scene. use scenePos() as already advised.

HelderC
2nd October 2012, 02:40
Ah, ok... finally I think I got it.

Thank you guys.