[pyqt5]pyqt5界面鼠标移动不触发鼠标移动事件

有如下代码:

import sys
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QPainter, QPen, QPixmap, QPainterPath, QFont, QColor, QBrush
from PyQt5.QtWidgets import QApplication, QWidget
import numpy as np


class DemoMouseEvent(QWidget):
    def __init__(self, parent=None):
        super(DemoMouseEvent, self).__init__(parent)
        # 设置窗口标题
        self.setWindowTitle('鼠标事件演示')
        # 设置窗口大小
        self.setFixedSize(480, 320)

        self.beginPoint = QPoint()  # 起始点
        self.endPoint = QPoint()  # 结束点

        self.pixmap = QPixmap(self.rect().size())
        self.pixmap.fill(Qt.lightGray)
        self.copt_pixmap =self.pixmap.copy()
        self.cur_x = 0
        self.cur_y = 0


    def draw(self, painter):
        path = QPainterPath()
        f = QFont('黑体', 10)
        point = QPoint(20, 20)
        path.addText(point, f, "世界您好")
        point1 = QPoint(50, 50)
        point2 = QPoint(self.cur_x, self.cur_y)
        path.moveTo(point)
        path.lineTo(point1)
        path.lineTo(point2)
        path.lineTo(point)
        path.addEllipse(point, 5, 5)
        painter.fillPath(path, QColor(0, 255, 0, 128))
        painter.drawPath(path)

    # 重绘窗口事件
    def paintEvent(self, event):
        self.pixmap=self.copt_pixmap.copy()
        pp = QPainter(self.pixmap)
        pp.setPen(QPen(Qt.blue, 2))  # 设置画笔
        self.draw(pp)
        # 绘制直线
        pp.drawLine(self.beginPoint, self.endPoint)
        # 上一直线的终点就是下一直线的起点
        self.beginPoint = self.endPoint

        # 在画布上画出
        painter = QPainter(self)
        painter.drawPixmap(0, 0, self.pixmap)


    def wheelEvent(self, ev):
        mods = ev.modifiers()
        # print('mods=', mods)
        delta = ev.angleDelta()
        # print('delta=', delta)
        if QtCore.Qt.ControlModifier == int(mods):
            if int(delta.y()) > 0:
                print("ctrl 向上滚轮")
            else:
                print("ctrl 向下滚轮")

    def mousePressEvent(self, event):
        # 鼠标左键按下
        if event.button() == Qt.LeftButton:
            self.startPoint = event.pos()

    def mouseReleaseEvent(self, event):
        # 鼠标左键释放
        if event.button() == Qt.LeftButton:
            self.endPoint = event.pos()
            # 重新绘制
            self.update()

    def mouseMoveEvent(self, event):
        self.cur_x = event.pos().x()
        self.cur_y = event.pos().y()
        self.update()
        print('x={},y={}'.format(self.cur_x,self.cur_y))
        # 鼠标左键按下的同时移动鼠标
        if event.buttons() and Qt.LeftButton:
            self.endPoint = event.pos()
            # 重新绘制
            self.update()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DemoMouseEvent()
    window.show()
    sys.exit(app.exec())

你会发现鼠标在界面上无法移动,触发不了鼠标移动事件,原来默认是没有开启鼠标追踪,只需要在构造函数加上

self.setMouseTracking(True)

即可触发鼠标移动事件。

猜你喜欢

转载自blog.csdn.net/FL1623863129/article/details/131529026