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:
- Since I used
selffor mouseevents, the error says:
object has no attribute ‘self.startx’ — (How should I associate a widget to mouseevents in PyQt?) paintEvent()gets called even when i move the mouse around the app.
Thanks in advance…
I would recommend making the line a seperate object that gets created once you release the mouse. To do so create a new class:
Then I would define your mouse events like follows.
This should allow the user to click and drag the mouse and then upon releasing the mouse it should draw the line and not effect whatever else is drawn. I usually do things in QGraphicsScenes and it is a little bit different, but the concept should be about the same for this. If you want to have the line being drawn as the user drags the mouse I know how to do that also, but the way I know is much more complicated than this and I would recommend using a QGraphicsScene to handle that, just message me if you want me to explain how I have done it.