Important: Please read the Qt Code of Conduct -

[SOLVED] Cropping an image using QLabel and QPixmap

  • Hi,
    I want to take a screenshot of my desktop screen and then crop that image by drawing a rectangle on it. So for I am able to capture the screenshot as QPixmap, set it on QLabel and displayed as a window (window.showMaximized()). I am also able to draw a rectangle on QLabel using mouse events and paintEvent of QLabel.
    The problem is that, when the paintEvent is called to draw the rectangle, the actual image vanishes from the QLabel.
    How can I draw a rectangle on QLabel without loosing the pixmap?
    Here is the code:
    class Label(QLabel):
    def init(self, parent = None):
    super(Label, self).init(parent)
    self.mousePos = QPoint()
    self.mouseDown = False
    self.rect = QRect()

    def mousePressEvent(self, event):
        self.mouseDown = True
        self.mousePos = event.pos()
    def mouseReleaseEvent(self, event):
    def mouseMoveEvent(self, event):
        if self.mouseDown:
    def paintEvent(self, event):
        if self.rect.x() > 0:
            painter = QPainter(self)    
            painter.setPen(QPen(, 1, Qt.SolidLine));


  • Moderators

    for such purposes check QRubberBand class on top (as a child widget) of the label

  • Thank you very much :) It worked like a charm.
    btw, how to make this post as "solved"? I am new to

  • Moderators

    just edit your first post and prepend [SOLVED] to the title.

Log in to reply