PDA

View Full Version : Associating widgets to mouseevents properly



ladiesfinger
8th February 2011, 16:12
I'm using PyQt4 and i want to draw a line based on user's click on an existing image which is displayed as an imagelabel . The image shows properly and after a clicking an icon in toolbar , the user will draw a line on the image .

I've overridden the mousePressEvent() and mouseReleaseEvent() to get the x,y positions. I've defined paintEvent() to draw the line .



def mousePressEvent(self,event):
self.startx=event.x()
self.starty=event.y()
def mouseReleaseEvent(self,event):
self.endx=event.x()
self.endy=event.y()

def paintEvent(self,event):
painter=QPainter()
painter.begin(self)
painter.setPen(QPen(Qt.darkGray,3))
painter.drawLine(self.startx,self.starty,self.endx ,self.endy)
painter.end()

PROBLEM :

i )Since i used 'self' for mouseevents , the error says: object has no attribute 'self.startx' - ( How should i associate a widget to mouseevents in PyQt ? )
ii )paintEvent() gets called even when i move the mouse around the app.

thanx in advance..

ladiesfinger
9th February 2011, 17:40
I've found a way to avoid unnecessary calling of paintEvent() by defining that in a separate class . It will get called only after releasing the mouse .


class line(QtGui.QWidget):
def __init__(self, point1, point2):
self.p1 = point1
self.p2 = point2

def paintEvent(self,event):
painter=QPainter()
painter.begin(self)
painter.setPen(QPen(Qt.darkGray,3))
painter.drawLine(self.p1,self.p2)
painter.end()
def mousePressEvent(self,event):
self.startx=event.x()
self.starty=event.y()
def mouseReleaseEvent(self,event):
self.endx=event.x()
self.endy=event.y()
newLine = line(QPoint(self.startx, self.starty),QPoint(self.endx,self.endy))


But the problem now is :
paintEvent() doesn't get called .
The constructor of that object gets called . ( i've added print() statements to find out the flow of control )

Anyone know why paintEvent doesn't get called ?