Search code examples
pythonqtpython-3.xpyqtpyqt5

How to draw a line from mouse to a point in PyQt5?


Here is my code:

import sys
from PyQt5.QtWidgets import (QApplication, QLabel, QWidget)
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt

class MouseTracker(QWidget):
    distance_from_center = 0
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setMouseTracking(True)

    def initUI(self):
        self.setGeometry(200, 200, 1000, 500)
        self.setWindowTitle('Mouse Tracker')
        self.label = QLabel(self)
        self.label.resize(500, 40)
        self.show()

    def mouseMoveEvent(self, event):
        distance_from_center = round(((event.y() - 250)**2 + (event.x() - 500)**2)**0.5)
        self.label.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()) + "Distance from center: " + str(distance_from_center))       

        q = QPainter()  #Painting the line
        q.begin(self)
        q.drawLine(event.x(), event.y(), 250, 500)
        q.end()

    def drawPoints(self, qp, x, y):
        qp.setPen(Qt.red)
        qp.drawPoint(x, y)

app = QApplication(sys.argv)
ex = MouseTracker()
sys.exit(app.exec_())

What I'm trying to do is paint a simple line from the position of the mouse to the middle of the widget using this:

        q = QPainter()  #Painting the line
        q.begin(self)
        q.drawLine(event.x(), event.y(), 250, 500)
        q.end()

But when I run it, no line is visible. What do I need to do?


Solution

  • You must implement the function QPaintEvent, in this function you must draw the line, in addition you must call the function update() to update the drawing.

    import sys
    from PyQt5.QtWidgets import (QApplication, QLabel, QWidget)
    from PyQt5.QtGui import QPainter, QColor, QPen
    from PyQt5.QtCore import Qt
    
    class MouseTracker(QWidget):
        distance_from_center = 0
        def __init__(self):
            super().__init__()
            self.initUI()
            self.setMouseTracking(True)
    
        def initUI(self):
            self.setGeometry(200, 200, 1000, 500)
            self.setWindowTitle('Mouse Tracker')
            self.label = QLabel(self)
            self.label.resize(500, 40)
            self.show()
            self.pos = None
    
        def mouseMoveEvent(self, event):
            distance_from_center = round(((event.y() - 250)**2 + (event.x() - 500)**2)**0.5)
            self.label.setText('Coordinates: ( %d : %d )' % (event.x(), event.y()) + "Distance from center: " + str(distance_from_center))       
            self.pos = event.pos()
            self.update()
    
        def paintEvent(self, event):
            if self.pos:
                q = QPainter(self)
                q.drawLine(self.pos.x(), self.pos.y(), 500, 250)
    
    
    app = QApplication(sys.argv)
    ex = MouseTracker()
    sys.exit(app.exec_())
    

    Output:

    enter image description here