PaintEvent () in PyQt called unnecessarily

I am using PyQt4 and I want to draw a line based on a user click on an existing image that displays as a label. The image is displayed correctly, and after clicking the icon on the toolbar, the user drew a line on the image.

I redefined mousePressEvent()and mouseReleaseEvent()to get the positions x, y. I determined paintEvent()to draw a 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:

  • As I used selffor mouseevents, the error says: the object does not have the attribute "self.startx" - (How to link the widget with mouseevents in PyQt?)
  • paintEvent() gets called even when I move the mouse around the application.

Thanks in advance...

+3
source share
1 answer

, . :

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(QtCore.QPoint(self.startx, self.starty), QtCore.QPoint(self.endx, self.endy))

, , , , . QGraphicsScenes, , . , , , , , , , , , QGraphicsScene , , , , .

+5

Source: https://habr.com/ru/post/1790754/


All Articles