0

I would like draw a rectangle above QPixmap on QLabel (with PyQT5). My purpose is the next:

  • First Click: To define the top-left corner.
  • Move mouse: To draw a rectangle that depends on the position of mouse. Only one rectangle.
  • Second Click: To confirm the position of the bottom-right corner and draw the definitive rectangle.

Actually, I have a code than allows do the actions of First Click and Second Click, but not drawing while move the mouse. I have used the paintEvent and mousePresEvent.

        pixmap_ed = QPixmap(f"{self.image}")
        pixmap_ed_scaled = pixmap_ed.scaled(int(self.QLabel.width()), int(self.QLabel.height()), QtCore.Qt.KeepAspectRatio)
        self.QLabel.setPixmap(pixmap_ed_scaled)

    def paintEvent(self,event):
        if self.flag_dibujar == True and self.primer_click == 1 and self.segundo_click == 1:
            painter = QPainter(self.QLabel.pixmap())
            pen = QPen()
            pen.setColor(QtGui.QColor('green'))
            pen.setWidth(3)
            painter.setPen(pen)

            painter.drawRect(self.beginX,self.beginY, self.endX-self.beginX,self.endY-self.beginY)
            self.update()
            self.QLabel.update()

            self.primer_click = 0
            self.segundo_click = 0

    def mousePresEvent(self, event):
        if self.flag_dibujar == True:
            if self.primer_click == 0 and event.button() == QtCore.Qt.LeftButton:
                self.begin = event.pos()
                self.beginX = int(self.begin.x())
                self.beginY= int(self.begin.y()) 

                self.QLabel.update()
                self.primer_click = 1
            else:
                self.end = event.pos()
                self.endX = int(self.end.x())
                self.endY = int(self.end.y())

                self.QLabel.update()
                self.segundo_click = 1
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jose David
  • 39
  • 9
  • Please provide a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – musicamante Jul 29 '20 at 14:25
  • Yes, I know the mouseMoveEvent, but when I use this method, painter draws rectangles in each position of mouse. I want only one rectangle that variate his shape since the first click position and confirm this shape with the second click. Do you understand me? – Jose David Jul 29 '20 at 15:38

0 Answers0