Search code examples
python-3.xcoordinatesmouseeventpyside6

Pyside6 mouse coordinate relative to image


Let suppose I have an image correctly rendered in a QLabel

As I want to get mouse position relative to the image I'm subclassing QLabel and reimplant mouseMoveEvent(self,event) and then build the source_image from this class.Rendering is Ok, but how do I get the event.x() from the parent class ?

I know I have to connect the instance to the ImLabel signals but i'm stuck with implementation.

class ImLabel(QLabel):
    def __init__(self):
        super().__init__()

    on_mouse_move = Signal()

    def mouseMoveEvent(self, event):
        print(event.x(), event.y())
        super(ImLabel, self).mouseMoveEvent(event)
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.source_image = ImLabel()
        self.source_image.on_mouse_move.connect(self.mouseMoveEvent)
        ...
        self.cursor = QLabel("cursor : ")
        ...
    def mouseMoveEvent(self,event):
        self.cursor.setText('Mouse coords: ( %d : %d )' % (event.x(), event.y()))

Solution

  • Finnally this is the way I made it :

    class ImLabel(QLabel):
        def __init__(self):
            super().__init__()
    
        def mouseMoveEvent(self, event):
            super(ImLabel, self).mouseMoveEvent(event)
            self.x,self.y = event.x(),event.y()
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
    
        ...
    
        def mouseMoveEvent(self,event):
            self.cursor.setText('Mouse coords: ( %d : %d )' % (self.source_image.x,self.source_image.y))