I'm working on a GUI application and I have a problem with the construction of QRect by mouse tracking within an image.
In deed, I want to draw a single rectangle on the window by using mouseMoveEvent.
I started to draw on the window itself but it doesn't work.
I also tried to use true coordinates rather than QPoint object but the effect is the same.
The MRE Code example :
class Window(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Python')
# setting geometry of window
self.setGeometry(100, 100, 600, 400)
#Display layouts
self.zone_plot = QGridLayout()
self.center_layout = QVBoxLayout()
#Image creation
path = '/home/lidaoa/PycharmProjects/stars.jpeg' #path to change
self.image = QPixmap(path)
self.image = self.image.scaled(700,500, Qt.KeepAspectRatio, Qt.FastTransformation)
self.lab_im = QLabel()
self.lab_im.setPixmap(self.image)
self.lab_im.adjustSize()
#Events to draw on the image
self.lab_im.mousePressEvent, self.lab_im.mouseMoveEvent, self.lab_im.mouseReleaseEvent = self.press_zone, self.track_zone, self.release_zone
self.flag = False
#Initialization of points
self.begin,self.dest = QPoint(),QPoint()
self.center_layout.addWidget(self.lab_im,alignment=Qt.AlignCenter)
self.zone_plot.addLayout(self.center_layout,1,1)
self.setLayout(self.zone_plot)
self.show()
def paintEvent(self,event):
if not self.flag:
return None
qpaint = QPainter(self.lab_im.pixmap())
qpaint.setPen(QColor(200,0,0))
qpaint.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform,True)
if not self.begin.isNull() and not self.dest.isNull():
rect = QRect(self.begin,self.dest).normalized()
qpaint.drawRect(rect)
qpaint.end()
del qpaint
def press_zone(self,event):
self.flag = True
if event.buttons() & Qt.LeftButton:
self.begin = event.pos()
self.dest = self.begin
self.update()
def track_zone(self, event):
if event.buttons() & Qt.LeftButton:
self.dest = event.pos()
self.update()
def release_zone(self,event):
if event.buttons() & Qt.LeftButton:
rect = QRect(self.begin,self.dest).normalized()
qpaint = QPainter(self.lab_im.pixmap())
qpaint.drawRect(rect)
self.begin, self.dest = QPoint(),QPoint()
self.update()
self.flag = False
# App creation
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())