原文: http://zetcode.com/gui/pyqt5/eventssignals/

在 PyQt5 编程教程的这一部分中,我们将探讨应用中发生的事件和信号。

事件

GUI 应用是事件驱动的。 事件主要由应用的用户生成。 但是它们也可以通过其他方式生成。 例如互联网连接,窗口管理器或计时器。 当我们调用应用的exec_()方法时,应用进入主循环。 主循环获取事件并将其发送到对象。

在事件模型中,有三个参与者:

  • 事件来源
  • 事件对象
  • 事件目标

事件源是状态更改的对象。 它生成事件。事件对象(事件)将状态更改封装在事件源中。事件目标是要通知的对象。 事件源对象将处理事件的任务委托给事件目标。

PyQt5 具有独特的信号和槽机制来处理事件。 信号和槽用于对象之间的通信。 当发生特定事件时,会发出信号。槽可以是任何 Python 可调用的。 发出连接信号时,将调用槽。

信号和槽

这是一个简单的示例,展示了 PyQt5 中的信号和槽。

sigslot.py

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we connect a signal
  6. of a QSlider to a slot of a QLCDNumber.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: January 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import Qt
  13. from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider,
  14. QVBoxLayout, QApplication)
  15. class Example(QWidget):
  16. def __init__(self):
  17. super().__init__()
  18. self.initUI()
  19. def initUI(self):
  20. lcd = QLCDNumber(self)
  21. sld = QSlider(Qt.Horizontal, self)
  22. vbox = QVBoxLayout()
  23. vbox.addWidget(lcd)
  24. vbox.addWidget(sld)
  25. self.setLayout(vbox)
  26. sld.valueChanged.connect(lcd.display)
  27. self.setGeometry(300, 300, 250, 150)
  28. self.setWindowTitle('Signal and slot')
  29. self.show()
  30. if __name__ == '__main__':
  31. app = QApplication(sys.argv)
  32. ex = Example()
  33. sys.exit(app.exec_())

在我们的示例中,我们显示QtGui.QLCDNumberQtGui.QSlider。 我们通过拖动滑块来更改lcd编号。

  1. sld.valueChanged.connect(lcd.display)

在这里,我们将滑块的valueChanged信号连接到lcd号的display槽。

发送器是发送信号的对象。接收器是接收信号的对象。槽是对信号做出反应的方法。

PyQt5 中的事件和信号 - 图1

图:信号和槽

重新实现事件处理器

PyQt5 中的事件通常通过重新实现事件处理器来处理。

escape.py

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we reimplement an
  6. event handler.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import Qt
  13. from PyQt5.QtWidgets import QWidget, QApplication
  14. class Example(QWidget):
  15. def __init__(self):
  16. super().__init__()
  17. self.initUI()
  18. def initUI(self):
  19. self.setGeometry(300, 300, 250, 150)
  20. self.setWindowTitle('Event handler')
  21. self.show()
  22. def keyPressEvent(self, e):
  23. if e.key() == Qt.Key_Escape:
  24. self.close()
  25. if __name__ == '__main__':
  26. app = QApplication(sys.argv)
  27. ex = Example()
  28. sys.exit(app.exec_())

在我们的示例中,我们重新实现了keyPressEvent()事件处理器。

  1. def keyPressEvent(self, e):
  2. if e.key() == Qt.Key_Escape:
  3. self.close()

如果单击“退出”按钮,则应用终止。

事件对象

事件对象是一个 Python 对象,其中包含许多描述事件的属性。 事件对象特定于生成的事件类型。

eventobject.py

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we display the x and y
  6. coordinates of a mouse pointer in a label widget.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import Qt
  13. from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QLabel
  14. class Example(QWidget):
  15. def __init__(self):
  16. super().__init__()
  17. self.initUI()
  18. def initUI(self):
  19. grid = QGridLayout()
  20. x = 0
  21. y = 0
  22. self.text = "x: {0}, y: {1}".format(x, y)
  23. self.label = QLabel(self.text, self)
  24. grid.addWidget(self.label, 0, 0, Qt.AlignTop)
  25. self.setMouseTracking(True)
  26. self.setLayout(grid)
  27. self.setGeometry(300, 300, 350, 200)
  28. self.setWindowTitle('Event object')
  29. self.show()
  30. def mouseMoveEvent(self, e):
  31. x = e.x()
  32. y = e.y()
  33. text = "x: {0}, y: {1}".format(x, y)
  34. self.label.setText(text)
  35. if __name__ == '__main__':
  36. app = QApplication(sys.argv)
  37. ex = Example()
  38. sys.exit(app.exec_())

在此示例中,我们在标签小部件中显示了鼠标指针的 x 和 y 坐标。

  1. self.text = "x: {0}, y: {1}".format(x, y)
  2. self.label = QLabel(self.text, self)

x 和 y 坐标显示在QLabel小部件中。

  1. self.setMouseTracking(True)

默认情况下,鼠标跟踪是禁用的,因此,仅在移动鼠标时按下至少一个鼠标按钮时,窗口小部件才会接收鼠标移动事件。 如果启用了鼠标跟踪,则即使未按任何按钮,窗口小部件也会接收鼠标移动事件。

  1. def mouseMoveEvent(self, e):
  2. x = e.x()
  3. y = e.y()
  4. text = "x: {0}, y: {1}".format(x, y)
  5. self.label.setText(text)

e是事件对象; 它包含有关已触发事件的数据; 在我们的例子中,是一个鼠标移动事件。 使用x()y()方法,我们可以确定鼠标指针的 x 和 y 坐标。 我们构建字符串并将其设置为标签小部件。

PyQt5 中的事件和信号 - 图2

图:事件对象

事件发送者

有时很方便地知道哪个窗口小部件是信号的发送者。 为此,PyQt5 具有sender()方法。

eventsource.py

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we determine the event sender
  6. object.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
  13. class Example(QMainWindow):
  14. def __init__(self):
  15. super().__init__()
  16. self.initUI()
  17. def initUI(self):
  18. btn1 = QPushButton("Button 1", self)
  19. btn1.move(30, 50)
  20. btn2 = QPushButton("Button 2", self)
  21. btn2.move(150, 50)
  22. btn1.clicked.connect(self.buttonClicked)
  23. btn2.clicked.connect(self.buttonClicked)
  24. self.statusBar()
  25. self.setGeometry(300, 300, 290, 150)
  26. self.setWindowTitle('Event sender')
  27. self.show()
  28. def buttonClicked(self):
  29. sender = self.sender()
  30. self.statusBar().showMessage(sender.text() + ' was pressed')
  31. if __name__ == '__main__':
  32. app = QApplication(sys.argv)
  33. ex = Example()
  34. sys.exit(app.exec_())

我们的示例中有两个按钮。 在buttonClicked()方法中,我们通过调用sender()方法来确定单击了哪个按钮。

  1. btn1.clicked.connect(self.buttonClicked)
  2. btn2.clicked.connect(self.buttonClicked)

两个按钮都连接到同一槽。

  1. def buttonClicked(self):
  2. sender = self.sender()
  3. self.statusBar().showMessage(sender.text() + ' was pressed')

我们通过调用sender()方法来确定信号源。 在应用的状态栏中,我们显示了被按下的按钮的标签。

PyQt5 中的事件和信号 - 图3

图:事件发送者

发射信号

QObject创建的对象可以发出信号。 以下示例说明了如何发出自定义信号。

customsignal.py

  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt5 tutorial
  5. In this example, we show how to
  6. emit a custom signal.
  7. Author: Jan Bodnar
  8. Website: zetcode.com
  9. Last edited: August 2017
  10. """
  11. import sys
  12. from PyQt5.QtCore import pyqtSignal, QObject
  13. from PyQt5.QtWidgets import QMainWindow, QApplication
  14. class Communicate(QObject):
  15. closeApp = pyqtSignal()
  16. class Example(QMainWindow):
  17. def __init__(self):
  18. super().__init__()
  19. self.initUI()
  20. def initUI(self):
  21. self.c = Communicate()
  22. self.c.closeApp.connect(self.close)
  23. self.setGeometry(300, 300, 290, 150)
  24. self.setWindowTitle('Emit signal')
  25. self.show()
  26. def mousePressEvent(self, event):
  27. self.c.closeApp.emit()
  28. if __name__ == '__main__':
  29. app = QApplication(sys.argv)
  30. ex = Example()
  31. sys.exit(app.exec_())

我们创建一个名为closeApp的新信号。 在鼠标按下事件期间发出此信号。 信号连接到QMainWindowclose()槽。

  1. class Communicate(QObject):
  2. closeApp = pyqtSignal()

使用pyqtSignal()作为外部Communicate类的类属性创建信号。

  1. self.c = Communicate()
  2. self.c.closeApp.connect(self.close)

定制的closeApp信号连接到QMainWindowclose()槽。

  1. def mousePressEvent(self, event):
  2. self.c.closeApp.emit()

当我们用鼠标指针单击窗口时,会发出closeApp信号。 该应用终止。

在 PyQt5 教程的这一部分中,我们介绍了信号和槽。