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