当前位置:   article > 正文

PyQt5事件处理机制学习笔记_self.update()

self.update()

Qt事件的类型

PyQt提供了5种事件处理和过滤的方法(由弱到强) 

  • 重新实现事件函数

比如mousePressEvent()、keyPressEvent()、paintEvent(),这是最常规的事件处理方法。

  1. import sys
  2. from PyQt5.QtCore import (QEvent, QTimer, Qt)
  3. from PyQt5.QtWidgets import (QApplication, QMenu, QWidget)
  4. from PyQt5.QtGui import QPainter
  5. class Widget(QWidget):
  6. def __init__(self, parent=None):
  7. super(Widget, self).__init__(parent)
  8. self.justDoubleClicked = False
  9. self.key = ""
  10. self.text = ""
  11. self.message = ""
  12. self.resize(400, 300)
  13. self.move(100, 100)
  14. self.setWindowTitle("Events")
  15. QTimer.singleShot(0, self.giveHelp) # 避免窗口大小重绘事件的影响,可以把参数0改变成3000(3秒),然后在运行,就可以明白这行代码的意思。
  16. def giveHelp(self):
  17. self.text = "请点击这里触发追踪鼠标功能"
  18. self.update() # 重绘事件,也就是触发paintEvent函数。
  19. '''重新实现关闭事件'''
  20. def closeEvent(self, event):
  21. print("Closed")
  22. '''重新实现上下文菜单事件'''
  23. def contextMenuEvent(self, event):
  24. menu = QMenu(self)
  25. oneAction = menu.addAction("&One")
  26. twoAction = menu.addAction("&Two")
  27. oneAction.triggered.connect(self.one)
  28. twoAction.triggered.connect(self.two)
  29. if not self.message:
  30. menu.addSeparator()
  31. threeAction = menu.addAction("Thre&e")
  32. threeAction.triggered.connect(self.three)
  33. menu.exec_(event.globalPos())
  34. '''上下文菜单槽函数'''
  35. def one(self):
  36. self.message = "Menu option One"
  37. self.update()
  38. def two(self):
  39. self.message = "Menu option Two"
  40. self.update()
  41. def three(self):
  42. self.message = "Menu option Three"
  43. self.update()
  44. '''重新实现绘制事件'''
  45. def paintEvent(self, event):
  46. text = self.text
  47. i = text.find("\n\n")
  48. if i >= 0:
  49. text = text[0:i]
  50. if self.key: # 若触发了键盘按钮,则在文本信息中记录这个按钮信息。
  51. text += "\n\n你按下了: {0}".format(self.key)
  52. painter = QPainter(self)
  53. painter.setRenderHint(QPainter.TextAntialiasing)
  54. painter.drawText(self.rect(), Qt.AlignCenter, text) # 绘制信息文本的内容
  55. if self.message: # 若消息文本存在则在底部居中绘制消息,5秒钟后清空消息文本并重绘。
  56. painter.drawText(self.rect(), Qt.AlignBottom | Qt.AlignHCenter,
  57. self.message)
  58. QTimer.singleShot(5000, self.clearMessage)
  59. QTimer.singleShot(5000, self.update)
  60. '''清空消息文本的槽函数'''
  61. def clearMessage(self):
  62. self.message = ""
  63. '''重新实现调整窗口大小事件'''
  64. def resizeEvent(self, event):
  65. self.text = "调整窗口大小为: QSize({0}, {1})".format(
  66. event.size().width(), event.size().height())
  67. self.update()
  68. '''重新实现鼠标释放事件'''
  69. def mouseReleaseEvent(self, event):
  70. # 若鼠标释放为双击释放,则不跟踪鼠标移动
  71. # 若鼠标释放为单击释放,则需要改变跟踪功能的状态,如果开启跟踪功能的话就跟踪,不开启跟踪功能就不跟踪
  72. if self.justDoubleClicked:
  73. self.justDoubleClicked = False
  74. else:
  75. self.setMouseTracking(not self.hasMouseTracking()) # 单击鼠标
  76. if self.hasMouseTracking():
  77. self.text = "开启鼠标跟踪功能.\n" + \
  78. "请移动一下鼠标!\n" + \
  79. "单击鼠标可以关闭这个功能"
  80. else:
  81. self.text = "关闭鼠标跟踪功能.\n" + \
  82. "单击鼠标可以开启这个功能"
  83. self.update()
  84. '''重新实现鼠标移动事件'''
  85. def mouseMoveEvent(self, event):
  86. if not self.justDoubleClicked:
  87. globalPos = self.mapToGlobal(event.pos()) # 窗口坐标转换为屏幕坐标
  88. self.text = """鼠标位置:
  89. 窗口坐标为:QPoint({0}, {1})
  90. 屏幕坐标为:QPoint({2}, {3}) """.format(event.pos().x(), event.pos().y(), globalPos.x(), globalPos.y())
  91. self.update()
  92. '''重新实现鼠标双击事件'''
  93. def mouseDoubleClickEvent(self, event):
  94. self.justDoubleClicked = True
  95. self.text = "你双击了鼠标"
  96. self.update()
  97. '''重新实现键盘按下事件'''
  98. def keyPressEvent(self, event):
  99. self.key = ""
  100. if event.key() == Qt.Key_Home:
  101. self.key = "Home"
  102. elif event.key() == Qt.Key_End:
  103. self.key = "End"
  104. elif event.key() == Qt.Key_PageUp:
  105. if event.modifiers() & Qt.ControlModifier:
  106. self.key = "Ctrl+PageUp"
  107. else:
  108. self.key = "PageUp"
  109. elif event.key() == Qt.Key_PageDown:
  110. if event.modifiers() & Qt.ControlModifier:
  111. self.key = "Ctrl+PageDown"
  112. else:
  113. self.key = "PageDown"
  114. elif Qt.Key_A <= event.key() <= Qt.Key_Z:
  115. if event.modifiers() & Qt.ShiftModifier:
  116. self.key = "Shift+"
  117. self.key += event.text()
  118. if self.key:
  119. self.key = self.key
  120. self.update()
  121. else:
  122. QWidget.keyPressEvent(self, event)
  123. '''重新实现其他事件,适用于PyQt没有提供该事件的处理函数的情况,Tab键由于涉及焦点切换,不会传递给keyPressEvent,因此,需要在这里重新定义。'''
  124. def event(self, event):
  125. if (event.type() == QEvent.KeyPress and
  126. event.key() == Qt.Key_Tab):
  127. self.key = "在event()中捕获Tab键"
  128. self.update()
  129. return True
  130. return QWidget.event(self, event)
  131. if __name__ == "__main__":
  132. app = QApplication(sys.argv)
  133. form = Widget()
  134. form.show()
  135. app.exec_()
  1. # -*- coding: utf-8 -*-
  2. from PyQt5.QtGui import *
  3. from PyQt5.QtCore import *
  4. from PyQt5.QtWidgets import *
  5. import sys
  6. class EventFilter(QDialog):
  7. def __init__(self, parent=None):
  8. super(EventFilter, self).__init__(parent)
  9. self.setWindowTitle("事件过滤器")
  10. self.label1 = QLabel("请点击")
  11. self.label2 = QLabel("请点击")
  12. self.label3 = QLabel("请点击")
  13. self.LabelState = QLabel("test")
  14. self.image1 = QImage("images/cartoon1.ico")
  15. self.image2 = QImage("images/cartoon1.ico")
  16. self.image3 = QImage("images/cartoon1.ico")
  17. self.width = 600
  18. self.height = 300
  19. self.resize(self.width, self.height)
  20. self.label1.installEventFilter(self)
  21. self.label2.installEventFilter(self)
  22. self.label3.installEventFilter(self)
  23. mainLayout = QGridLayout(self)
  24. mainLayout.addWidget(self.label1, 500, 0)
  25. mainLayout.addWidget(self.label2, 500, 1)
  26. mainLayout.addWidget(self.label3, 500, 2)
  27. mainLayout.addWidget(self.LabelState, 600, 1)
  28. self.setLayout(mainLayout)
  29. def eventFilter(self, watched, event):
  30. if watched == self.label1: # 只对label1的点击事件进行过滤,重写其行为,其他的事件会被忽略
  31. if event.type() == QEvent.MouseButtonPress: # 这里对鼠标按下事件进行过滤,重写其行为
  32. mouseEvent = QMouseEvent(event)
  33. if mouseEvent.buttons() == Qt.LeftButton:
  34. self.LabelState.setText("按下鼠标左键")
  35. elif mouseEvent.buttons() == Qt.MidButton:
  36. self.LabelState.setText("按下鼠标中间键")
  37. elif mouseEvent.buttons() == Qt.RightButton:
  38. self.LabelState.setText("按下鼠标右键")
  39. '''转换图片大小'''
  40. transform = QTransform()
  41. transform.scale(0.5, 0.5)
  42. tmp = self.image1.transformed(transform)
  43. self.label1.setPixmap(QPixmap.fromImage(tmp))
  44. if event.type() == QEvent.MouseButtonRelease: # 这里对鼠标释放事件进行过滤,重写其行为
  45. self.LabelState.setText("释放鼠标按钮")
  46. self.label1.setPixmap(QPixmap.fromImage(self.image1))
  47. return QDialog.eventFilter(self, watched, event) # 其他情况会返回系统默认的事件处理方法。
  48. if __name__ == '__main__':
  49. app = QApplication(sys.argv)
  50. dialog = EventFilter()
  51. dialog.show()
  52. sys.exit(app.exec_())

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

闽ICP备14008679号