0

I have a QLabel that displays a Pixmap and I want the user to be able to drag inside that label and draw a rectangle.

Just like how this code works.

However my label is loaded from a .ui file so I cant just do self.label = MyLabel() in my window class as it'll get rid of my existing label and its styling, I can access my label directly using self.myLabel ("myLabel" being its name in the .ui file). I dont understand how I can subclass my existing label or is it possible to implement this without subclassing?

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class MyLabel(QLabel):
    def __init__(self):
        super().__init__()
        self.begin = QPoint()
        self.end = QPoint()
        self.rectangle = None

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        self.rectangle = QRect(self.begin, self.end)
        painter.drawRect(self.rectangle)

    def mousePressEvent(self, event):
        self.begin = event.pos()
        self.end = event.pos()
        self.update()

    def mouseMoveEvent(self, event):
        self.end = event.pos()
        self.update()

    def mouseReleaseEvent(self, event):
        self.end = event.pos()
        self.update()
        print((self.rectangle.size()))



class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.label = MyLabel()
        self.setCentralWidget(self.label)
        self.setGeometry(100, 100, 800, 800)
        self.setWindowTitle('Rectangle Drawing')


if __name__ == '__main__':
    app = QApplication([])
    window = MyApp()
    window.show()
    app.exec_()

Saif eldeen Adel
  • 318
  • 3
  • 15
  • Add a basic QLabel in Designer, promote it as `MyLabel` and set the name of the file that contains the class as "header file" (without the `.py` extension, just like it was a python module). – musicamante Mar 18 '23 at 18:11

0 Answers0