当前位置:   article > 正文

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

pyqt5鼠标事件不响应

有如下代码:

  1. import sys
  2. from PyQt5 import QtCore
  3. from PyQt5.QtCore import Qt, QPoint
  4. from PyQt5.QtGui import QPainter, QPen, QPixmap, QPainterPath, QFont, QColor, QBrush
  5. from PyQt5.QtWidgets import QApplication, QWidget
  6. import numpy as np
  7. class DemoMouseEvent(QWidget):
  8. def __init__(self, parent=None):
  9. super(DemoMouseEvent, self).__init__(parent)
  10. # 设置窗口标题
  11. self.setWindowTitle('鼠标事件演示')
  12. # 设置窗口大小
  13. self.setFixedSize(480, 320)
  14. self.beginPoint = QPoint() # 起始点
  15. self.endPoint = QPoint() # 结束点
  16. self.pixmap = QPixmap(self.rect().size())
  17. self.pixmap.fill(Qt.lightGray)
  18. self.copt_pixmap =self.pixmap.copy()
  19. self.cur_x = 0
  20. self.cur_y = 0
  21. def draw(self, painter):
  22. path = QPainterPath()
  23. f = QFont('黑体', 10)
  24. point = QPoint(20, 20)
  25. path.addText(point, f, "世界您好")
  26. point1 = QPoint(50, 50)
  27. point2 = QPoint(self.cur_x, self.cur_y)
  28. path.moveTo(point)
  29. path.lineTo(point1)
  30. path.lineTo(point2)
  31. path.lineTo(point)
  32. path.addEllipse(point, 5, 5)
  33. painter.fillPath(path, QColor(0, 255, 0, 128))
  34. painter.drawPath(path)
  35. # 重绘窗口事件
  36. def paintEvent(self, event):
  37. self.pixmap=self.copt_pixmap.copy()
  38. pp = QPainter(self.pixmap)
  39. pp.setPen(QPen(Qt.blue, 2)) # 设置画笔
  40. self.draw(pp)
  41. # 绘制直线
  42. pp.drawLine(self.beginPoint, self.endPoint)
  43. # 上一直线的终点就是下一直线的起点
  44. self.beginPoint = self.endPoint
  45. # 在画布上画出
  46. painter = QPainter(self)
  47. painter.drawPixmap(0, 0, self.pixmap)
  48. def wheelEvent(self, ev):
  49. mods = ev.modifiers()
  50. # print('mods=', mods)
  51. delta = ev.angleDelta()
  52. # print('delta=', delta)
  53. if QtCore.Qt.ControlModifier == int(mods):
  54. if int(delta.y()) > 0:
  55. print("ctrl 向上滚轮")
  56. else:
  57. print("ctrl 向下滚轮")
  58. def mousePressEvent(self, event):
  59. # 鼠标左键按下
  60. if event.button() == Qt.LeftButton:
  61. self.startPoint = event.pos()
  62. def mouseReleaseEvent(self, event):
  63. # 鼠标左键释放
  64. if event.button() == Qt.LeftButton:
  65. self.endPoint = event.pos()
  66. # 重新绘制
  67. self.update()
  68. def mouseMoveEvent(self, event):
  69. self.cur_x = event.pos().x()
  70. self.cur_y = event.pos().y()
  71. self.update()
  72. print('x={},y={}'.format(self.cur_x,self.cur_y))
  73. # 鼠标左键按下的同时移动鼠标
  74. if event.buttons() and Qt.LeftButton:
  75. self.endPoint = event.pos()
  76. # 重新绘制
  77. self.update()
  78. if __name__ == '__main__':
  79. app = QApplication(sys.argv)
  80. window = DemoMouseEvent()
  81. window.show()
  82. sys.exit(app.exec())

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

self.setMouseTracking(True)

即可触发鼠标移动事件。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/897376
推荐阅读
相关标签
  

闽ICP备14008679号