如何在 PyQt5 中从鼠标到点画一条线?

2022-01-12 00:00:00 python python-3.x pyqt pyqt5 qt

问题描述

这是我的代码:

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?


解决方案

你必须实现函数QPaintEvent,在这个函数中你必须画线,另外你必须调用函数update() 更新绘图.

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(), 250, 500)


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

输出:

相关文章