Qt: convert a mouse press QPoint to a relative point inside a QRect

Viewed 24

I have two QRects lined side by side:

def paintEvent(self, event):
    painter = QPainter(self)
    self.rect1 = QRect(0, 0, 500, 40)
    painter.fillRect(self.rect1, Qt.GlobalColor.black)
    self.rect2 = QRect(500, 0, 500, 40)
    painter.fillRect(self.rect2, Qt.GlobalColor.white)

If user clicks somewhere in second QRect, I want to know the location of the click relative to the (0, 0) of the QRect:

def mousePressEvent(self, event):
    pos = event.pos()

    if self.rect2.contains(pos):
        relative_pos = QPoint(pos.x() - self.rect2.x(), pos.y() - self.rect2.y())

Is there a built-in way to do this?

0 Answers
Related